有一个启动脚本到NodeJS CLI

你如何添加一个启动脚本到node.js cli? 例如require模块或设置一些选项?

编辑:我正在谈论服务器端,即我想能够在我的系统的任何部分启动node CLI,并预先在全局级别上启动脚本(类似于一个bashrc )。

当我读你的文章,我意识到,目前的Node.js REPL糟透了! 所以我做了一个关于你的post的function的基本演示,我把它叫做摇动 。

在这里,我将解释代码的每一行:

 #!/usr/bin/env node 

这是shebang,它确保它作为Node运行

 const repl = require("repl"), vm = require("vm"), fs = require("fs"), path = require("path"), spawn = require("child_process").spawn, package = require("./package"); 

导入所有的包,你知道演习

 function insertFile(file, context) { fs.readFile(file, function(err, contents) { if (err) throw err; vm.runInContext(contents, context); }); } 

我定义了一个函数来插入一个文件到一个VM上下文(REPL是)

 if (process.argv.includes("--global")) { console.log(path.resolve(__dirname, ".noderc")); 

显示全局.noderc的位置

 /** Hijack the REPL, if asked **/ } else if (process.argv.length < 3 || process.argv.includes("-i") || process.argv.includes("--interactive")) { 

这开始是代码的肉。 这检测用户是否想要进入REPL模式

  console.log(`rattle v${package.version}`); var cmdline = repl.start("> "), context = cmdline.context; 

使用标准提示创buildrepl,并获取VM上下文

  /** Insert config files **/ fs.access(localrc = path.resolve(process.cwd(), ".noderc"), function(noLocal) { if (!noLocal) { insertFile(localrc, context); } }); 

testing是否有一个本地.noderc,如果有插入到上下文中

  fs.access(globalrc = path.resolve(__dirname, ".noderc"), function(noGlobal) { if (!noGlobal && globalrc !== localrc) { insertFile(globalrc, context); } }); 

testing全局.noderc,然后插入它

 } else { /** Defer to node.js **/ var node = spawn("node", process.argv.slice(2)); node.stdout.pipe(process.stdout); node.stderr.pipe(process.stderr); } 

剩下的只是将代码传递给节点,因为它不是REPL的东西

写起来很有趣,希望对某人有用。

祝你好运!