Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node.js equivalent of python's if __name__ == '__main__' [duplicate]

Tags:

node.js

I'd like to check if my module is being included or run directly. How can I do this in node.js?

like image 942
nornagon Avatar asked Feb 13 '11 01:02

nornagon


2 Answers

The docs describe another way to do this which may be the preferred method:

When a file is run directly from Node, require.main is set to its module.

To take advantage of this, check if this module is the main module and, if so, call your main code:

var fnName = function() {     // main code }  if (require.main === module) {     fnName(); } 

EDIT: If you use this code in a browser, you will get a "Reference error" since "require" is not defined. To prevent this, use:

if (typeof require !== 'undefined' && require.main === module) {     fnName(); } 
like image 164
Stephen Emslie Avatar answered Oct 02 '22 07:10

Stephen Emslie


if (!module.parent) {   // this is the main module } else {   // we were require()d from somewhere else } 

EDIT: If you use this code in a browser, you will get a "Reference error" since "module" is not defined. To prevent this, use:

if (typeof module !== 'undefined' && !module.parent) {   // this is the main module } else {   // we were require()d from somewhere else or from a browser } 
like image 32
nornagon Avatar answered Oct 02 '22 07:10

nornagon