Can I know, in node.js, if my script is being run directly or being loaded by another script?
The accepted answer is fine. I'm adding this one from the official documentation for completeness:
Accessing the main module
When a file is run directly from Node, require.main
is set to its module
. That means that you can determine whether a file has been run directly by testing
require.main === module
For a file "foo.js"
, this will be true
if run via node foo.js
, but false
if run by require('./foo')
.
Because module
provides a filename
property (normally equivalent to __filename
), the entry point of the current application can be obtained by checking require.main.filename
.
Both options !module.parent
and require.main === module
work.If you are interested in more details please read my detailed blog post about this topic.