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

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:

function myMain() {
    // main code
}

if (require.main === module) {
    myMain();
}

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) {
    myMain();
}

Leave a Comment