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


当前回答

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

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

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

其他回答

你也可以用类似于@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

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

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

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

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

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

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

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

make-runnable试试。

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

现在你可以做:

node db.js init

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