Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import a Node.js module function, without invoking it

Tags:

node.js

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?

like image 547
Allyl Isocyanate Avatar asked Sep 08 '26 01:09

Allyl Isocyanate


2 Answers

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.

like image 196
sleighty Avatar answered Sep 10 '26 15:09

sleighty


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 };
like image 24
Alex Avatar answered Sep 10 '26 15:09

Alex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!