Skip to content

Instantly share code, notes, and snippets.

@mrnejc
Created May 8, 2015 09:24
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 mrnejc/3976cddab9715eb0c4c0 to your computer and use it in GitHub Desktop.
Save mrnejc/3976cddab9715eb0c4c0 to your computer and use it in GitHub Desktop.
using command line parameters in node.js application
// have to have args npm package
// npm install args --save
var args = require('args');
// defining command line options
var args_options = args.Options.parse([
{
name: 'port',
shortName: 'P',
type: 'int',
required: false,
defaultValue: 3000,
help: 'run server on specified port',
},
{
name: 'help',
shortName: 'h',
type: 'bool',
required: false,
default: false,
help: 'print this help info',
}
]);
var argv;
try {
// parser will parse process.args by default
argv = new args.parser().parse(args_options);
} catch(e) {
// will force the print of help page, which in term causes exit
argv = { help: true };
console.log('Error parsing command line parameters');
console.log('%s %s %s', e.name, e.src, e.value);
}
// if help is requested print it and exit
if(argv.help === true) {
console.log(args_options.getHelp());
process.exit(0);
}
// accessing options is quite simple
console.log('listening on port %d', argv.port);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment