George Bailey George Bailey - 1 year ago 120
Node.js Question

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

How can I detect whether my Node.JS file was called using SH:

node path-to-file
or JS:

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?

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

See documentation for this here:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download