Skip to content

Instantly share code, notes, and snippets.

@joemaller
Created August 25, 2017 17:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joemaller/276dc9998fd744abb6827a8d6e8b7011 to your computer and use it in GitHub Desktop.
Save joemaller/276dc9998fd744abb6827a8d6e8b7011 to your computer and use it in GitHub Desktop.
Run node.js modules from the command line

Add one line to a node.js module and it becomes a callable script:

// hello-module.js
module.exports = function() {
return "Hello!";
};

if (!module.parent) module.exports();

Now that module can be called from the command line:

$ node hello-module.js
Hello!

The module.parent property will be null when the script is called from the command line. When module.parent is falsey, the module just calls the function which was attached to module.exports.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment