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


当前回答

有时你想通过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方法。

灵感来自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()

希望这能有所帮助

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

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

这段代码将立即执行并调用init函数。