有一个启动脚本到NodeJS CLI
问题描述:
如何将启动脚本添加到node.js
cli?例如。为require
ing模块或设置一些选项?有一个启动脚本到NodeJS CLI
编辑: 我谈论服务器侧,即我希望能够在我的系统的任何部分,以启动node
CLI并使其预加载启动脚本上(类同一个bashrc
)全球一级。
答
当我阅读你的文章时,我意识到当前的Node.js REPL很糟糕!所以我做了一个关于你的帖子功能的基本演示,我把它叫做rattle。
在这里,我将解释代码的每一行:
#!/usr/bin/env 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;
创建REPL,与标准的提示,并获得VM上下文
/** Insert config files **/
fs.access(localrc = path.resolve(process.cwd(), ".noderc"), function(noLocal) {
if (!noLocal) {
insertFile(localrc, context);
}
});
测试,如果有一个地方.noderc,如果有插入它为背景
fs.access(globalrc = path.resolve(__dirname, ".noderc"), function(noGlobal) {
if (!noGlobal && globalrc !== localrc) {
insertFile(globalrc, context);
}
});
测试全球.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的东西
这很有趣写,并希望对某人有用。
祝你好运!
可能重复[JavaScript需要()在客户端](http://stackoverflow.com/questions/5168451/javascript-require-on-client-side) – Arthur
您可能将不得不效仿自己使用[REPL](https://nodejs.org/api/repl.html)API复制。很快我就会回家,如果你不知道,我会写一个基本的原型 – MayorMonty