Allyl Isocyanate
Allyl Isocyanate

Reputation: 13626

Import a Node.js module function, without invoking it

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?

Upvotes: 3

Views: 2161

Answers (3)

sleighty
sleighty

Reputation: 1075

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.

Upvotes: 4

Estus Flask
Estus Flask

Reputation: 222379

This means that init() shouldn't be executed automatically, and there should be different entry points.

One entry point for programmatic use (test.js). Another one to be used as command-line executable (test-cli.js):

require('./test.js').init()

This is a common scenario for NPM packages. CLI entry point can be specified in package bin.

Upvotes: 1

Alex
Alex

Reputation: 2174

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 };

Upvotes: 2

Related Questions