Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

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 command 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 command line');
} else {
    console.log('required as a module');
}
like image 819
dwhieb Avatar asked Oct 17 '22 13:10

dwhieb


1 Answers

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:

if (process.argv[1].indexOf("sayHello.mjs") > -1){
    sayHello();
} else {
    export default sayHello;
}
like image 81
Steve Avatar answered Oct 20 '22 05:10

Steve