Created
May 8, 2015 09:24
-
-
Save mrnejc/3976cddab9715eb0c4c0 to your computer and use it in GitHub Desktop.
using command line parameters in node.js application
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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