Created
May 2, 2017 10:50
-
-
Save nin-jin/a39b93d94f334cd567c59446fc6e8a6b to your computer and use it in GitHub Desktop.
NodeJS arguments processing
This file contains 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
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