Javascript 'require()' method
Question: 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?


Answer: Via [fuyushimoya](http://stackoverflow.com/users/1737627/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](https://nodejs.org/api/modules.html#modules_accessing_the_main_module)

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
    }
    

