1

In python, when you import a module the statements inside the 'if name == main' block of the imported module is not executed.

Is there any equivalent approach which can prevents the execution of unwanted statements in the imported module in javascript?

Gul Ershad
1,7712 gold badges26 silver badges33 bronze badges
asked Jul 5, 2015 at 9:51
1

2 Answers 2

5

Via fuyushimoya's comment.

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').

Node.js documentation

So:

if (require.main === module) {
 // Code that runs only if the module is executed directly
} else {
 // Code that runs only if the code is loaded as a module
}

3 Comments

I'm not sure his condition though, as I'm still learning python, if in python this way is to create a master-slave structure, then maybe cluster with cluster.isMaster is what he wants?
@fuyushimoya .. in python it is .. if __name__ == '__main__': //code thank you :)
In addition to this answer, common pattern to include some statements in module which will not be executed when module is required is: if (!module.parent) { // not executed with require } else { // executed only with require }
-2

Simply group your statements inside functions, and export the functions you want.

exports.function1 = new function () {
 //some code
}
function function2() {
 //some other code 
}

More on it here.

answered Jul 5, 2015 at 10:08

1 Comment

You seem to have completely misunderstood the question.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.