我正在用Node写一个web应用程序。如果我有一些带有init函数的JS文件,我怎么从命令行调用这个函数呢?
当前回答
也许这个方法不是你想要的,但谁知道它会有帮助呢
index.js
const arg = process.argv.splice(2);
function printToCli(text){
console.log(text)
}
switch(arg[0]){
case "--run":
printToCli("how are you")
break;
default: console.log("use --run flag");
}
并运行命令node。——运行
命令行
probuss-MacBook-Air:fb_v8 probus$ node . --run
how are you
probuss-MacBook-Air:fb_v8 probus$
你可以添加更多的arg[0], arg[1], arg[2]…和更多的
对于节点。——运行-myarg1 -myarg2
其他回答
也许这个方法不是你想要的,但谁知道它会有帮助呢
index.js
const arg = process.argv.splice(2);
function printToCli(text){
console.log(text)
}
switch(arg[0]){
case "--run":
printToCli("how are you")
break;
default: console.log("use --run flag");
}
并运行命令node。——运行
命令行
probuss-MacBook-Air:fb_v8 probus$ node . --run
how are you
probuss-MacBook-Air:fb_v8 probus$
你可以添加更多的arg[0], arg[1], arg[2]…和更多的
对于节点。——运行-myarg1 -myarg2
make-runnable试试。
在db.js中,添加require('make-runnable');直到最后。
现在你可以做:
node db.js init
任何进一步的参数都将以列表或键值对的形式传递给init方法。
简单的方法:
假设你在项目结构的helpers目录下有一个db.js文件。
现在进入助手目录,进入节点控制台
helpers $ node
2)需要db.js文件
> var db = require("./db")
3)调用你的函数(在你的情况下是init())
> db.init()
希望这能有所帮助
灵感来自https://github.com/DVLP/run-func/blob/master/index.js
我创建了https://github.com/JiangWeixian/esrua
如果文件index.ts
export const welcome = (msg: string) => {
console.log(`hello ${msg}`)
}
你就跑
esrua ./index.ts welcome -p world
将输出hello world
不评论你为什么想这样做,或者什么可能是更标准的做法:这里是你的问题的解决方案....请记住,命令行所需的引号类型可能会有所不同。
在你的db.js中,导出init函数。有很多方法,比如:
module.exports.init = function () {
console.log('hi');
};
然后像这样调用它,假设你的db.js和你的命令提示符在同一个目录下:
node -e 'require("./db").init()'
如果你的db.js是一个模块db.js。Mjs,使用动态导入加载模块:
node -e 'import("./db.mjs").then( loadedModule => loadedModule.init() )'
对于其他读者来说,OP的init函数可以被称为任何东西,这并不重要,这只是问题中使用的特定名称。