我正在用Node写一个web应用程序。如果我有一些带有init函数的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

根据其他答案,将以下内容添加到someFile.js

module.exports.someFunction = function () {
  console.log('hi');
};

然后可以将以下内容添加到package.json

"scripts": {
   "myScript": "node -e 'require(\"./someFile\").someFunction()'"
}

然后,您可以从终端进行呼叫

npm run myScript

我发现这是一种更容易记住和使用命令的方法

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());'

我做了一个IIFE,就像这样:

(() => init())();

这段代码将立即执行并调用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();