Check require.main to test if a Node.js file is run directly

In Node, when a file is run directly from the command line, require.main is set to its module. Hence require.main === module tells you whether or not your script was invoked directly or required by another file.

A JavaScript "main" idiom:

//#!/usr/bin/env node
// file: example.js

function main() {
  // ...
}

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

The main method will run if example.js is invoked via node example.js or ./example.js but not when required within another script (via require('./example'), for example).

A CoffeeScript "main" idiom (using classes, although it doesn't have to):

#!/usr/bin/env coffee
# file: example.coffee
class Example
  main:()->
    # ...

if require.main is module
  (new Example()).main()

The main method will run if example.coffee is invoked via coffee example.coffee or ./example.coffee but not when required within another script (via require('./example'), for example).

Also see the nodejs.org docs.

Published 3 Mar 2013

 

This page was generated at 9:56 PM on 15 Jan 2016.
Copyright © 1999 - 2016 Rodney Waldhoff.