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?
-
2Accessing the main module#, you mean this?fuyushimoya– fuyushimoya2015年07月05日 09:56:24 +00:00Commented Jul 5, 2015 at 9:56
2 Answers 2
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').
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
cluster.isMaster
is what he wants?if __name__ == '__main__': //code
thank you :)if (!module.parent) { // not executed with require } else { // executed only with require }
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.