/ #javascript #node 

Detect if the current file/module is the entrypoint or import/require-d in Node.js

How does one identify whether a JavaScript file is being run directly (node file.js) or it’s being import/require-d (require('./file') in another JS file).

In Python the pattern leverages the __main__ property in modules like so:

if __name__ == '__main__':
  # do something
  # or not
  pass

The equivalent code in Node.js/JavaScript would be:

if (require.main === module) {
  // do something
  // or nothing
}
Table of Contents

Detecting whether a module/file is the Node.js entrypoint or required/imported

Say we have a file/module entry-or-not.js:

function isEntryPoint() {
  return require.main === module;
}

console.log(isEntryPoint());

If we run the file directly it should return true:

$ node entry-or-not.js
true

If require through the REPL whether we eval or actually go into the REPL, it should be false:

$ node -e "require('./entry-or-not')"
false

and

$ node
> require('./entry-or-not')
false
{}

If we require/import from another module another-module.js:

require('./entry-or-not');

And run that module as the Node.js entry point.

$ node another-module.js
false

Further Reading

Accessing the main module - Node.js Documentation.

unsplash-logoBenjamin Lambert

Looking for a new job? Take Triplebyte’s quiz and have top tech companies pitch you!

Author

Hugo Di Francesco

A Software Engineer and recovering Frontend Engineer who is big on Node.js, queues and Vue(s). He shares practical JavaScript tips for the developer who wants to get things done on Code with Hugo. University College London (UCL), MEng Mathematical Computation Graduate.

Subscribe for Enterprise Node.js and JavaScript Guides

Build your web platform with modern Node.js/JavaScript best-practices, tools and patterns