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.
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:
Via the command line:
node --experimental-modules sayHello.mjs
Via an ES6 import statement in another script:
import sayHello from './sayHello.mjs';
sayHello();
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');
}
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With