Node.JS: Detect if called through require or directly by command line


Question

How can I detect whether my Node.JS file was called using SH:node path-to-file or JS:require('path-to-file')?

This is the Node.JS equivalent to my previous question in Perl: How can I run my Perl script only if it wasn't loaded with require?

1
267
5/23/2017 11:47:25 AM

Accepted Answer

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

410
2/19/2019 3:50:37 PM

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.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon