我正在用Node写一个web应用程序。如果我有一些带有init函数的JS文件,我怎么从命令行调用这个函数呢?
当前回答
你也可以用类似于@LeeGoddard answer的ts-node运行TypeScript。 在我的例子中,我想分别使用app和init进行测试。
// app.ts
export const app = express();
export async function init(): Promise<void> {
// app init logic...
}
npx ts-node -e 'require("./src/app").init();'
npx ts-node -e 'import("./src/app").then(a => a.init());' // esmodule
其他回答
这个有点脏,但很好用:)
我将从脚本中调用main()函数。以前我只是在脚本的末尾调用main。然而,我确实添加了一些其他函数并将它们从脚本中导出(在代码的其他部分使用函数)-但我不想每次在其他脚本中导入其他函数时都执行main()函数。
所以我这样做了, 在我的脚本中,我删除了对main()的调用,而不是在脚本的末尾,我把这个检查:
if (process.argv.includes('main')) {
main();
}
所以当我想在CLI中调用这个函数时:node src/myScript.js main
根据其他答案,将以下内容添加到someFile.js
module.exports.someFunction = function () {
console.log('hi');
};
然后可以将以下内容添加到package.json
"scripts": {
"myScript": "node -e 'require(\"./someFile\").someFunction()'"
}
然后,您可以从终端进行呼叫
npm run myScript
我发现这是一种更容易记住和使用命令的方法
灵感来自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
如果你的文件只包含你的函数,例如:
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
也许这个方法不是你想要的,但谁知道它会有帮助呢
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