Last Updated: February 25, 2016
·
805
· futuraprime

Execute code if your node.js script is run from the command line

In python, there's a really handy convention to allow your code to be either modular or executable:

if __name__ == '__main__':
    print 'foo'

If you run python foo.py from the command line, it'll output foo, but if you import foo from another python script, it won't.

Node.js' equivalent of this is:

if (require.main === module) {
    console.log('foo');
}