gpt4 book ai didi

javascript - npm 全局包 : Reference content files from package

转载 作者:IT老高 更新时间:2023-10-28 23:21:55 24 4
gpt4 key购买 nike

我正在构建一个将在全局范围内安装的 npm 包。是否可以将非代码文件与可从代码文件引用的代码文件一起安装?

例如,如果我的包包含 someTextFile.txt 和一个 module.js 文件(而我的 package.json 包含 "bin": {"someCommand":"./module.js"}) 我可以将 someTextFile.txt 的内容读入 module.js 的内存中吗>?我该怎么做?

最佳答案

以下是一个将文件(字符串)的内容加载到全局范围内的模块示例。

core.js : the main module file (entry point of package.json)

//:Understanding: module.exports
module.exports = {
reload:(cb)=>{ console.log("[>] Magick reloading to memory"); ReadSpellBook(cb)}
}
//:Understanding: global object
//the following function is only accesible by the magick module
const ReadSpellBook=(cb)=>{
require('fs').readFile(__dirname+"/spellBook.txt","utf8",(e,theSpells)=>{
if(e){ console.log("[!] The Spell Book is MISSING!\n"); cb(e)}
else{
console.log("[*] Reading Spell Book")
//since we want to make the contents of .txt accesible :
global.SpellBook = theSpells // global.SpellBook is now shared accross all the code (global scope)
cb()//callBack
}
})
}
//·: Initialize :.
console.log("[+] Time for some Magick!")
ReadSpellBook((e)=>e?console.log(e):console.log(SpellBook))

spellBook.txt

ᚠ   ᚡ   ᚢ   ᚣ   ᚤ   ᚥ   ᚦ   ᚧ   ᚨ   ᚩ   ᚪ   ᚫ   ᚬ   ᚭ   ᚮ   ᚯ
ᚰ ᚱ ᚲ ᚳ ᚴ ᚵ ᚶ ᚷ ᚸ ᚹ ᚺ ᚻ ᚼ ᚽ ᚾ ᚿ
ᛀ ᛁ ᛂ ᛃ ᛄ ᛅ ᛆ ᛇ ᛈ ᛉ ᛊ ᛋ ᛌ ᛍ ᛎ ᛏ
ᛐ ᛑ ᛒ ᛓ ᛔ ᛕ ᛖ ᛗ ᛘ ᛙ ᛚ ᛛ ᛜ ᛝ ᛞ ᛟ
ᛠ ᛡ ᛢ ᛣ ᛤ ᛥ ᛦ ᛧ ᛨ ᛩ ᛪ ᛫ ᛬ ᛭ ᛮ ᛯ

如果您在另一段代码中需要它,您将看到它如何打印到控制台并自行初始化。

如果要实现手动初始化,只需删除最后 3 行 (·: Initialize :.) 并使用 reload() :

const magick = require("core.js")
magick.reload((error)=>{ if(error){throw error}else{
//now you know the SpellBook is loaded
console.log(SpellBook.length)
})

关于javascript - npm 全局包 : Reference content files from package,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50026612/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com