(Updated: )
/ #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.

Photo by Benjamin Lambert

Author

Hugo Di Francesco

Co-author of "Professional JavaScript", "Front-End Development Projects with Vue.js" with Packt, "The Jest Handbook" (self-published). Hugo runs the Code with Hugo website helping over 100,000 developers every month and holds an MEng in Mathematical Computation from University College London (UCL). He has used JavaScript extensively to create scalable and performant platforms at companies such as Canon, Elsevier and (currently) Eurostar.

Get The Jest Handbook (100 pages)

Take your JavaScript testing to the next level by learning the ins and outs of Jest, the top JavaScript testing library.