Quickstart With Vorpal
by Thomas Urban
The code bases on an approach provided at GitHub.
const Path = require( "path" );
const Minimist = require( "minimist" );
const Vorpal = require( "vorpal" )();
let argv = process.argv.slice( 0 );
let args = Minimist( argv.slice( 2 ) );
let repl = !( args._ && args._.length ) && !( args.h || args.help );
if ( args.h || args.help ) {
argv = [].concat.apply( argv.slice( 0, 2 ).concat( "help" ), argv.slice( 2 ).filter( i => i[0] !== "-" ) );
}
Vorpal.catch( "[words...]", "Catches incorrect commands" )
.action( function( args, cb ) {
this.log( ( args.words ? args.words.join( " " ) : "<unknown>" ) + " is not a valid command." );
cb();
} );
Vorpal
.command( "some-cmd", "some command" )
.action( function( args, cb ) {
// invokes command code in module providing vorpal and arguments, supporting promise as result
Promise.resolve( require( "./actions/some-cmd" )( this, args ) ).then( repl ? cb : null );
} );
if ( repl ) {
Vorpal
.delimiter( "$" )
.show();
} else {
Vorpal
.on( "client_command_executed", function() {
process.exit( 0 )
} )
.delimiter( "$" )
.parse( argv.slice( 0 ) );
}
This code provides the following semantics:
mycmd
- start in REPL modemycmd -h
- show generic help and exitmycmd --help
- show generic help and exitmycmd help
- show generic help and exitmycmd some-cmd
- run selected command and exitmycmd some-cmd -h
- show help onsome-cmd
mycmd some-cmd --help
- show help onsome-cmd
mycmd help some-cmd
- show help onsome-cmd