Last Updated: February 25, 2016
·
982
· 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');
}

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside