我正在用Node写一个web应用程序。如果我有一些带有init函数的JS文件,我怎么从命令行调用这个函数呢?


当前回答

如果你把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();

其他回答

根据其他答案,将以下内容添加到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

简单的方法:

假设你在项目结构的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

这个有点脏,但很好用:)

我将从脚本中调用main()函数。以前我只是在脚本的末尾调用main。然而,我确实添加了一些其他函数并将它们从脚本中导出(在代码的其他部分使用函数)-但我不想每次在其他脚本中导入其他函数时都执行main()函数。

所以我这样做了, 在我的脚本中,我删除了对main()的调用,而不是在脚本的末尾,我把这个检查:

if (process.argv.includes('main')) {
   main();
}

所以当我想在CLI中调用这个函数时:node src/myScript.js main