简体   繁体   English

通过命令行或 ES6 导入运行 Node.js 脚本

[英]Run Node.js script via command line or ES6 import

How do I write a Node script that can be run from either the command line or via an ES6 import statement?如何编写可以从命令行或通过 ES6 导入语句运行的 Node 脚本?

I am using the --experimental-modules flag and .mjs extension to run scripts as ES6 modules.我正在使用--experimental-modules标志和.mjs扩展.mjs脚本作为 ES6 模块运行。

Example例子

Say I have the following script in sayHello.mjs :假设我在sayHello.mjs有以下脚本:

export default function sayHello() {
  console.log(`Hello!`);
}

I would like to be able to use this script in the following two ways:我希望能够通过以下两种方式使用此脚本:

  1. Via the command line:通过命令行:

     node --experimental-modules sayHello.mjs
  2. Via an ES6 import statement in another script:通过另一个脚本中的 ES6 导入语句:

     import sayHello from './sayHello.mjs'; sayHello();

Details细节

I am looking for a solution similar to using module.main for CommonJS modules (this does not work for ES6 imports):我正在寻找类似于对 CommonJS 模块使用module.main的解决方案(这不适用于 ES6 导入):

if (require.main === module) {
    console.log('run from command line');
} else {
    console.log('required as a module');
}

You could try:你可以试试:

function sayHello() { console.log("Hello"); }
if (process.env.CL == 1){
    sayHello();
} else {
    export default sayHello;
}

From commandline, use:从命令行,使用:

CL=1 node --experimental-modules sayHello.mjs

Pretty simple, but it should work很简单,但它应该工作

Another option is to check process.argv[1] since it should always be the filename that was specified from the commandline :另一种选择是检查process.argv[1]因为它应该始终是从命令行指定的文件名

if (process.argv[1].indexOf("sayHello.mjs") > -1){
    sayHello();
} else {
    export default sayHello;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM