我正在用Node写一个web应用程序。如果我有一些带有init函数的JS文件,我怎么从命令行调用这个函数呢?
当前回答
简单的方法:
假设你在项目结构的helpers目录下有一个db.js文件。
现在进入助手目录,进入节点控制台
helpers $ node
2)需要db.js文件
> var db = require("./db")
3)调用你的函数(在你的情况下是init())
> db.init()
希望这能有所帮助
其他回答
不评论你为什么想这样做,或者什么可能是更标准的做法:这里是你的问题的解决方案....请记住,命令行所需的引号类型可能会有所不同。
在你的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函数可以被称为任何东西,这并不重要,这只是问题中使用的特定名称。
如果你的文件只包含你的函数,例如:
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
你也可以用类似于@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
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