Skip to content
Nathan Schwartz edited this page Jun 30, 2017 · 14 revisions

Vorpal

This page declares the API for the root of a Vorpal instance.

API

vorpal.parse(argv[, options])

Parses the process's process.argv arguments and executes the matching command.

vorpal
  .show()
  .parse(process.argv);
~$ node app.js foo
bar
app$
Options

When use: 'minimist' is passed in as an option, .parse will instead expose the minimist module's main method and return the results, executing no commands.

// Assuming the program was invoked with this command line:
// node index.js --file testing.txt -baz
var results = vorpal.parse(process.argv, {use: 'minimist'});
// results would be: { _: [], file: 'testing.txt', b: true, a: true, z: true }

vorpal.delimiter(string)

Sets the prompt delimiter for the given Vorpal instance.

new Vorpal().delimiter('unicorn-approved-app$');
~$ myglobalapp
unicorn-approved-app$ 
unicorn-approved-app$ exit -f
~$ 

vorpal.show()

Attaches the TTY's CLI prompt to that given instance of Vorpal.

// ... (your app's code)

vorpal
  .delimiter('pg-cli:')
  .show();
  
vorpal
  .command('sql <query>', 'Executes arbitrary sql.')
  .action(function(args, cb){
    return app.execSQL(args.query);
  });
$ node pgcli.js
Started interactive Postgres CLI.
pg-cli~$ 
pg-cli~$ sql 'select top 1 first_name from persons'
  
  first_name
-------------
  Joe

pg-cli~$

As a note, multiple instances of Vorpal can run in the same Node instance. However, only one can be 'attached' to your TTY. The last instance given the show() command will be attached, and the previously shown instances will detach.

var instances = []
for (var i = 0; i < 3; ++i) {
  instances[i] = new Vorpal()
    .delimiter('instance' + i + '~$')
    .command('switch <instance>', 'Switches prompt to another instance.')
    .action(function(args, cb){
      instances[args.instance].show();
      cb();
    })
}

instances[0].show();
$ node server.js
instance0~$ switch 1
instance1~$ switch 2
instance2~$ switch 0
instance0~$

vorpal.hide()

Dettaches the TTY's CLI prompt to that given instance of Vorpal.

// ... (your app's code)

vorpal
  .delimiter('pg-cli:')
  .show();
  
vorpal
  .command('disable', 'Disables Vorpal. No input will be read or accepted for 10 seconds.')
  .action(function(args, cb){
    vorpal.hide();
    setTimeout(function() { vorpal.show(); }, 10000);
  });

vorpal.find(string)

Returns a given command by its name. This is used instead of vorpal.command() as .command will overwrite a given command. If command is not found, undefined is returned.

  var help = vorpal.find('help');
  if (help) { 
    help.hidden() 
  }

vorpal.exec(command[, callback])

Executes an API command string. Returns a callback or Promise.

// Using Promises:
vorpal.exec('get ingredients').then(function(data){
  return vorpal.exec('roll dough');
}).then(function(data){
  return vorpal.exec('add cheese');
}).then(function(data){
  return vorpal.exec('add pepperoni');
}).then(function(data){
  return vorpal.exec('shape crust');
}).then(function(data){
  return vorpal.exec('insert into oven');
}).then(function(data){
  return vorpal.exec('wait 480000');
}).then(function(data){
  return vorpal.exec('remove from oven');
}).then(function(data){
  return vorpal.exec('enjoy');
}).catch(function(err){
  console.log('Error baking pizza: ' + err);
  app.orderOut();
});

// Using callbacks:
vorpal.exec('prepare pizza', function(err, data) {
  if (!err) {
    vorpal.exec('bake pizza', function(err, pizza){
      if (!err) {
        app.eat(pizza);
      }
    });
  }
});

Gotcha: Vorpal commands are executed in sync. If you call vorpal.exec from within a Vorpal command, it will not execute until the current command has been completed.

vorpal.execSync(command[, options])

Executes a synchronous Vorpal command.

console.log(vorpal.execSync('echo foo'));
// foo

Response is based on what is returned through the Vorpal command's action:

vorpal.command('echo [words...]').action(function (args, cb) {
  const resp = args.words.join(' ');
  // Logs to stdout
  this.log(resp);
  // Returns to an async `vorpal.exec()`
  cb(resp);
  // Returns to sync `vorpal.execSync()`
  return resp;
});
Options
  • fatal: When true, Vorpal will throw an error when the executed command errors. When false, the error will be returned silently. Defaults to false.

vorpal.log(string[, strings...])

Properly logs to stdout. Use this in the place of console.log.

The only exception is inside of a command.action() method, at which point you would use this.log. Refer to the CommandInstance wiki for more details.

// Correct. Properly redraws prompt
// after logging.
vorpal.log('Hello');

// Incorrect. Garbles logging into
// the user's prompt.
console.log('Hello');

This command is not supported in Vantage.js.

vorpal.history(id)

Sets up persistent history for your application.

The ID is a unique string you choose for your app, so the history does not cross up with other running Vorpal apps.

vorpal.history('iTunes-remote');

vorpal.localStorage(id)

Implements the W3C-compliant localStorage API.

The ID is a unique string you choose for your app, so the storage does not cross up with other running Vorpal apps. After initiating vorpal.localStorage, it exposes the regular localStorage API.

vorpal.localStorage('iTunes-remote');
vorpal.localStorage.setItem('foo', 'bar');
console.log(vorpal.localStorage.getItem('foo')); // -> bar

vorpal.help(function)

Overrides the default help results for Vorpal. Function passes in the user's attempted command that triggered the help. Expects a string to be returned, which Vorpal will print.

vorpal.help(function (cmd) {
  let result = `${cmd} is an invalid command.\n\n`;
  result += `Here's my custom help content!...`;
  return result;
});

If you want to access registered Vorpal commands, you can access them through this.commands, which returns an Array of them. Warning: Internal access to a Vorpal command's sub properties is not a frozen API feature an may change for something cleaner.

vorpal.pipe(function)

Captures all session stdout piped through Vorpal and passes it through a custom function. The string returned from the function is then logged.

var onStdout = function(stdout) {
  app.writeToLog(stdout);
  return '';
}

vorpal
  .pipe(onStdout);

vorpal.log('Hello');
vorpal.use(extension)

Vorpal supports command extensions and this is the primary reason for supporting sub-commands. For example, someone could create a suite of server diagnostic commands under the namespace system and publish it as vorpal-system.

The vorpal.use() method is for importing extensions. It expects a Node module (exposed as a function). You can also pass in the string of the module as an alternative, and vorpal will require it for you.

var system = require('vorpal-system');
vorpal.use(system);

/* 
  Your API would now include a suite of system commands:
  system list processes
  system status
  system ... etc.
*/
// Does the same thing as above.
vorpal.use('vorpal-system');
Clone this wiki locally