我正在用Node写一个web应用程序。如果我有一些带有init函数的JS文件,我怎么从命令行调用这个函数呢?
当前回答
如果你的文件只包含你的函数,例如:
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
其他回答
2022年更新-如果你已经切换到ES模块,你不能使用require技巧,你需要使用动态导入:
node -e 'import("./db.js").then(dbMod => dbMod.init());'
或者使用——experimental- specification -resolution=节点标志:
node --experimental-specifier-resolution=node -e 'import("./db").then(dbMod => dbMod.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
如果你想从你的。env文件中包含环境变量,你可以使用env-cmd:
npx env-cmd node -e 'require("./db").init()'
如果你想在文件中运行一个特定的函数,使用run-func:
npx env-cmd npx run-func db.js init someArg
或者,为已接受的答案提供一个参数,你必须这样做:
npx env-cmd node -e 'require("./db").init(someArg)'
在这里编写/更新表达式比为命令提供不同的参数更不显式(例如,当你回头检查时更容易错过),所以我建议使用env-cmd和run-func。
注意:必要时,我通常还会在后面加上——experimental-modules。
我做了一个IIFE,就像这样:
(() => init())();
这段代码将立即执行并调用init函数。
根据其他答案,将以下内容添加到someFile.js
module.exports.someFunction = function () {
console.log('hi');
};
然后可以将以下内容添加到package.json
"scripts": {
"myScript": "node -e 'require(\"./someFile\").someFunction()'"
}
然后,您可以从终端进行呼叫
npm run myScript
我发现这是一种更容易记住和使用命令的方法