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 mode
  • mycmd -h - show generic help and exit
  • mycmd --help - show generic help and exit
  • mycmd help - show generic help and exit
  • mycmd some-cmd - run selected command and exit
  • mycmd some-cmd -h - show help on some-cmd
  • mycmd some-cmd --help - show help on some-cmd
  • mycmd help some-cmd - show help on some-cmd

Go back