/ #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

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;


If we run the file directly it should return true:

$ node entry-or-not.js

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

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


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

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


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

$ node another-module.js

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!


Hugo Di Francesco

A Software Engineer who is big on Node.js, queues and Vue(s). Co-author of "Professional JavaScript" with Packt. 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.

Get Testing Superpowers with these Underused Jest Features

Subscribe for free resources that turbocharge your Jest tests and a discount on the "Advanced Jest Handbook"