Jac*_*lyk 10 javascript scaffolding node.js npm
我正在构建一个全局安装的npm包.是否可以将非代码文件与可以从代码文件引用的代码文件一起安装?
例如,如果我的包中包含someTextFile.txt
一个module.js
文件(和我的package.json
包含"bin": {"someCommand":"./module.js"}
),我可以在someTextFile.txt
内存中读取内容module.js
吗?我该怎么办?
以下是将文件(字符串)内容加载到全局范围的模块示例。
\n\n\n\n\ncore.js:主模块文件(package.json的入口点)
\n
//:Understanding: module.exports\nmodule.exports = {\n reload:(cb)=>{ console.log("[>] Magick reloading to memory"); ReadSpellBook(cb)}\n}\n//:Understanding: global object\n//the following function is only accesible by the magick module\nconst ReadSpellBook=(cb)=>{\n require(\'fs\').readFile(__dirname+"/spellBook.txt","utf8",(e,theSpells)=>{\n if(e){ console.log("[!] The Spell Book is MISSING!\\n"); cb(e)}\n else{ \n console.log("[*] Reading Spell Book") \n //since we want to make the contents of .txt accesible :\n global.SpellBook = theSpells // global.SpellBook is now shared accross all the code (global scope)\n cb()//callBack\n }\n })\n}\n//\xc2\xb7: Initialize :.\nconsole.log("[+] Time for some Magick!")\nReadSpellBook((e)=>e?console.log(e):console.log(SpellBook))\n
Run Code Online (Sandbox Code Playgroud)\n\n\n\n\n咒语书.txt
\n
\xe1\x9a\xa0 \xe1\x9a\xa1 \xe1\x9a\xa2 \xe1\x9a\xa3 \xe1\x9a\xa4 \xe1\x9a\xa5 \xe1\x9a\xa6 \xe1\x9a\xa7 \xe1\x9a\xa8 \xe1\x9a\xa9 \xe1\x9a\xaa \xe1\x9a\xab \xe1\x9a\xac \xe1\x9a\xad \xe1\x9a\xae \xe1\x9a\xaf\n\xe1\x9a\xb0 \xe1\x9a\xb1 \xe1\x9a\xb2 \xe1\x9a\xb3 \xe1\x9a\xb4 \xe1\x9a\xb5 \xe1\x9a\xb6 \xe1\x9a\xb7 \xe1\x9a\xb8 \xe1\x9a\xb9 \xe1\x9a\xba \xe1\x9a\xbb \xe1\x9a\xbc \xe1\x9a\xbd \xe1\x9a\xbe \xe1\x9a\xbf\n\xe1\x9b\x80 \xe1\x9b\x81 \xe1\x9b\x82 \xe1\x9b\x83 \xe1\x9b\x84 \xe1\x9b\x85 \xe1\x9b\x86 \xe1\x9b\x87 \xe1\x9b\x88 \xe1\x9b\x89 \xe1\x9b\x8a \xe1\x9b\x8b \xe1\x9b\x8c \xe1\x9b\x8d \xe1\x9b\x8e \xe1\x9b\x8f\n\xe1\x9b\x90 \xe1\x9b\x91 \xe1\x9b\x92 \xe1\x9b\x93 \xe1\x9b\x94 \xe1\x9b\x95 \xe1\x9b\x96 \xe1\x9b\x97 \xe1\x9b\x98 \xe1\x9b\x99 \xe1\x9b\x9a \xe1\x9b\x9b \xe1\x9b\x9c \xe1\x9b\x9d \xe1\x9b\x9e \xe1\x9b\x9f\n\xe1\x9b\xa0 \xe1\x9b\xa1 \xe1\x9b\xa2 \xe1\x9b\xa3 \xe1\x9b\xa4 \xe1\x9b\xa5 \xe1\x9b\xa6 \xe1\x9b\xa7 \xe1\x9b\xa8 \xe1\x9b\xa9 \xe1\x9b\xaa \xe1\x9b\xab \xe1\x9b\xac \xe1\x9b\xad \xe1\x9b\xae \xe1\x9b\xaf\n
Run Code Online (Sandbox Code Playgroud)\n\n如果您从另一段代码中需要它,您将看到它如何打印到控制台并自行初始化。
\n\n如果您想实现手动初始化,只需删除最后 3 行 ( \xc2\xb7: Initialize :.
) 并使用reload()
:
const magick = require("core.js")\nmagick.reload((error)=>{ if(error){throw error}else{ \n //now you know the SpellBook is loaded\n console.log(SpellBook.length)\n})\n
Run Code Online (Sandbox Code Playgroud)\n
归档时间: |
|
查看次数: |
175 次 |
最近记录: |