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

其他回答

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

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

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

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

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

npm run myScript

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

不评论你为什么想这样做,或者什么可能是更标准的做法:这里是你的问题的解决方案....请记住,命令行所需的引号类型可能会有所不同。

在你的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函数可以被称为任何东西,这并不重要,这只是问题中使用的特定名称。

有时你想通过CLI运行一个函数,有时你想从另一个模块请求它。以下是如何做到这两点。

// file to run
const runMe = () => {}
if (require.main === module) {
  runMe()
} 
module.exports = runMe

也许这个方法不是你想要的,但谁知道它会有帮助呢

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

make-runnable试试。

在db.js中,添加require('make-runnable');直到最后。

现在你可以做:

node db.js init

任何进一步的参数都将以列表或键值对的形式传递给init方法。