admin管理员组

文章数量:1388630

How do I write a Node script that can be run from either the mand line or via an ES6 import statement?

I am using the --experimental-modules flag and .mjs extension to run scripts as ES6 modules.

Example

Say I have the following script in 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 mand line:

    node --experimental-modules sayHello.mjs
    
  2. Via an ES6 import statement in another script:

    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):

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

How do I write a Node script that can be run from either the mand line or via an ES6 import statement?

I am using the --experimental-modules flag and .mjs extension to run scripts as ES6 modules.

Example

Say I have the following script in 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 mand line:

    node --experimental-modules sayHello.mjs
    
  2. Via an ES6 import statement in another script:

    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):

if (require.main === module) {
    console.log('run from mand line');
} else {
    console.log('required as a module');
}
Share Improve this question edited Jun 4, 2020 at 3:58 Sergey Vyacheslavovich Brunov 18.2k7 gold badges52 silver badges85 bronze badges asked Sep 20, 2018 at 17:55 dwhiebdwhieb 1,84620 silver badges31 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 4

You could try:

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

From mandline, 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 mandline:

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

本文标签: javascriptRun Nodejs script via command line or ES6 importStack Overflow