Can I know, in node.js, if my script is being run directly or being loaded by another script?

node.jsModule

node.js Problem Overview


I'm just getting started with node.js and I have some experience with Python. In Python I could check whether the __name__ variable was set to "__main__", and if it was I'd know that my script was being run directly. In that case I could run test code or make use of the module directly in other ways.

Is there anything similar in node.js?

node.js Solutions


Solution 1 - node.js

You can use module.parent to determine if the current script is loaded by another script.

e.g.

a.js:

if (!module.parent) {
    console.log("I'm parent");
} else {
    console.log("I'm child");
}

b.js:

require('./a')

run node a.js will output:

I'm parent

run node b.js will output:

I'm child

Solution 2 - node.js

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.

Solution 3 - node.js

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHubroView Question on Stackoverflow
Solution 1 - node.jsqiaoView Answer on Stackoverflow
Solution 2 - node.jsDavid BraunView Answer on Stackoverflow
Solution 3 - node.jsThorsten LorenzView Answer on Stackoverflow