I have a Node.js module with a function that is exported, and designed to be invoked when the script is run from the command line:
function init() {
console.log('initializing');
}
init();
module.exports = { init };
I'd like to require / import the underlying method in another module, without evaluating init. Unfortunately require seems to evaluate it:
> require('./test.js').init;
initializing
{ init: [Function: init] }
Is it possible to require this method, without evaluating it in this scenario?
How about putting the part you need to run when the script is invoked from the command line inside a check for require.main === module? That way, init() is only called if you're invoking that script using node test.js. So:
function init() {
console.log('initializing');
}
if (require.main === module) {
init();
}
module.exports = { init };
It kind of answers your question backwards, but I think this might be close to what you're looking for.
You might want to keep an eye out for changes to this feature with regards to the --experimental-modules flag.
Your issue is related to the fact that you invoke the init function yourself.
Just do not invoke it in the module which contains implementation instead invoke the function after requiring it inside any other module.
function init() {
console.log('initializing');
}
// warning! do not call invoke init function here
// init()
module.exports = { init };
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