Search code examples
node.js

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


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


Solution

  • CommonJS modules

    The Node.js CommonJS modules 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();
    }
    

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

    ECMAScript modules

    Since Node.js v20.11.0, import.meta.filename is available, allowing you to use:

    if (process.argv[1] === import.meta.filename) {
        myMain();
    }
    

    For older versions of Node.js, you can accomplish the same thing with:

    import { fileURLToPath } from 'node:url';
    
    if (process.argv[1] === fileURLToPath(import.meta.url)) {
        myMain();
    }