Skip to content

Instantly share code, notes, and snippets.

@nin-jin nin-jin/args.js
Created May 2, 2017

Embed
What would you like to do?
NodeJS arguments processing
var args = {}
process.argv.slice(2).forEach( param => {
var values = param.split( '=' )
var key = values.shift()
args[ key ] = ( args[ key ] || [] ).concat( values.join( '=' ) )
} )
var actions = {
'help help' : args => `help\t\tPrints help (default action)\n` ,
'help' : args => `\nSuper-puper server!\n${ actions['actions']() }${ actions['options']() }`,
'actions help' : args => `actions\t\tPrints all available actions\n` ,
'actions' : args => {
var res = `\nActions:\n\n`
Object.keys( actions ).forEach( path => {
if( !/ help$/.test( path ) ) return
res += actions[ path ]( args )
} )
return res
} ,
'options help' : args => `options\t\tPrints common options\n` ,
'options' : args => {
var res = `\nCommon options:\n\n`
res += `host=localhost\thost to bind server\n`
res += `port=80\t\tport to bind server\n`
return res
} ,
'server actions help' : args => `server actions\tPrints all actions supported by server\n` ,
'server actions' : args => {
var res = `\nServer actions:\n\n`
Object.keys( actions ).forEach( path => {
if( !/^server .+ help$/.test( path ) ) return
res += actions[ path ]( args )
} )
return res
} ,
'server start help' : args => `server start\tStarts server\n` ,
'server start' : args => {
return `Server started at ${ args.port || 80 } port`
} ,
'server stop help' : args => `server stop\tStops server\n` ,
'server stop' : args => {
return `Server stopped`
} ,
}
var keys = Object.keys( args )
while( keys.length ) {
var path = keys.join(' ')
var handler = actions[ path ]
if( handler ) break
keys.pop()
}
if( !keys.length ) handler = actions[ 'help' ]
console.log( handler( args ) )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.