An easier to use tool to manage command-line arguments and flags in nodejs
Install torko with npm
npm install torko
To Initilize, simply require and call torko
. Passing process.argv.slice(2)
as a parameter is optional.
const torko = require('torko')(); // requires and calls torko
console.log(torko);
Now,the above script with node index.js start --port 8080 -w
.
What are we doing?
- The first part
node index.js
says node to run the script. start
is the command we pass to torko. Commands must not start with '-' and they must be passed before flags and arguments.--port 8080
, hereport
is the argument and8080
is value.-w
is a flag. Flags don't contain value.
Now, if you've understood, let's focus on the output:
Torko { commands: [ 'start' ], args: { port: '8080' }, flags: [ 'w' ] }
commands
: Array of commandsargs
: Key:Value pair of arguments. Keys are without prefix.flags
: Array of flags without prefix.
.handle().command(<command>).by(<function>)
: Calls<function>
if<command>
was passed as command.handle().arg(<arg>).by(<function>)
: Calls<function>
with the value of as a parameter if<arg>
was passed as an argument..handle().flag(<flag>).by(<function>)
: Calls<function>
if<flag>
was passed as an flag.
Logs server starting
if start
was passed as a command
const torko = require('torko')();
torko.handle().command('start').by(() => {
console.log('server starting');
})
Gets port number
const torko = require('torko')();
torko.handle().arg('port').by(port_number => {
console.log(port);
});
Checks whether server should listen in production mode
const torko = require('torko')();
torko.handle().flag('production').by(()=> {
console.log('starting server in production');
});
- Report Bug Your feedbacks and suggestions are appreciated. Mail me at [email protected]