Detect if called through require or directly by command line

Solution 1:

if (require.main === module) {
    console.log('called directly');
} else {
    console.log('required as a module');
}

See documentation for this here: https://nodejs.org/docs/latest/api/modules.html#modules_accessing_the_main_module

Solution 2:

There is another, slightly shorter way (not outlined in the mentioned docs).

var runningAsScript = !module.parent;

I outlined more details about how this all works under the hood in this blog post.

Solution 3:

I was a little confused by the terminology used in the explanation(s). So I had to do a couple quick tests.

I found that these produce the same results:

var isCLI = !module.parent;
var isCLI = require.main === module;

And for the other confused people (and to answer the question directly):

var isCLI = require.main === module;
var wasRequired = !isCLI;

Solution 4:

Try this if you are using ES6 modules:

if (process.mainModule.filename === __filename) {
  console.log('running as main module')
}