A command middleware for nutty
npm install --save nutty-command
//Import dependenciesvarnutty=require('nutty');varcommand=require('nutty-command');//Initialize the clinutty.set('name','my-app');//Get the new test commandvarcommand_test=newcommand('test','Test the CLI');//Add the optionscommand_test.option({name: 'msg',detail: 'Print a message',default: 'No message'});command_test.option({name: 'upperCase',detail: 'Print the message in upper case',default: false});//Add the callback functioncommand_test.callback(function(args,body){//Check the upperCase optionif(args.options.upperCase!==false){//Get the message in upper caseargs.options.msg=args.options.msg.toUpperCase();}//Print the test messageconsole.log('Message: '+args.options.msg);});//Add the test commandnutty.use(command_test.build());//No command providednutty.use(function(args,body,next){returnconsole.error('No command provided');});//Run the CLInutty.run();In this example, when the user execute the test command of the CLI app, the provided callback fill be invoked:
my-app test
Message: No message
The user can add the msg option:
my-app test --msg "This is my message"
Message: This is my message
//Add with the upper case option
my-app test --msg "My test message" --upperCase
Message: MY TEST MESSAGE
Generate a new command object. The constructor accepts two arguments:
name: a string with the command name. If the first argument of the CLI matches this string, then the callback function provided will be invoked.description: a string with the command description.
Example:
varcmd=newcommand('test','Test the CLI');Add a new option parser for this command. The object must have the following keys:
name: a string with the option name (mandatory).detail: a string with the option detail.default: the option default value.
Example:
//Add an optioncmd.opt({name: 'option',detail: 'My option',default: ''});The function that will be invoked if the user runs this command. This function will be called with the same arguments described here, but without the next function.
Example:
//Callbackcmd.callback(function(args,body){//Do your magic here});Generate the middleware to be used with the nutty.use method.
MIT LICENSE © Josemi Juanes.