我正在用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
其他回答
灵感来自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
更新2020 - CLI
正如@mix3d指出的那样,你可以只运行一个命令,其中file.js是你的文件,someFunction是你的函数,后面有空格分隔的参数
npx run-func file.js someFunction "just some parameter"
就是这样。
在上面的例子中调用File.js
const someFunction = (param) => console.log('Welcome, your param is', param)
// exporting is crucial
module.exports = { someFunction }
更详细的描述
从CLI直接运行(全局)
安装
npm i -g run-func
使用方法,即运行函数“init”,它必须导出,见底部
run-func db.js init
or
从包运行。Json脚本(本地)
安装
npm i -S run-func
设置
"scripts": {
"init": "run-func db.js init"
}
使用
npm run init
参数个数
以下参数将作为函数参数传入init(param1, param2)
run-func db.js init param1 param2
重要的
函数(在本例中是init)必须在包含它的文件中导出
module.exports = { init };
或ES6导出
export { init };
如果你把db.js转换成一个模块,你可以从db_init.js和:node db_init.js中要求它。
db.js:
module.exports = {
method1: function () { ... },
method2: function () { ... }
}
db_init.js:
var db = require('./db');
db.method1();
db.method2();
简单的方法:
假设你在项目结构的helpers目录下有一个db.js文件。
现在进入助手目录,进入节点控制台
helpers $ node
2)需要db.js文件
> var db = require("./db")
3)调用你的函数(在你的情况下是init())
> db.init()
希望这能有所帮助
如果你的文件只包含你的函数,例如:
myFile.js:
function myMethod(someVariable) {
console.log(someVariable)
}
像这样从命令行调用它什么也不会发生:
node myFile.js
但是如果你改变你的文件:
myFile.js:
myMethod("Hello World");
function myMethod(someVariable) {
console.log(someVariable)
}
现在这将从命令行工作:
node myFile.js