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
Interested in Alpine.js?
Power up your debugging with the Alpine.js Devtools Extension for Chrome and Firefox. Trusted by over 15,000 developers (rated 4.5 ⭐️).
orJoin 1000s of developers learning about Enterprise-grade Node.js & JavaScript