API | CommandInstance

Armando Magalhães edited this page Jun 22, 2016 · 5 revisions

Command Instance

When the .action method is fired, the context of the method (this) exposes a commandInstance object.

The commandInstance in turn exposes additional methods for fine-grained control of the commands being executed.

API

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

Any and all logging in a .action method should be done through this.log, which operates just like console.log.

This ensures all stdout for your given Vorpal command is properly routed through any piped commands, and correctly renders it in your terminal.

Logging all stdout through this.log is important. Omitting this will result in unexpected behavior.

vorpal
  .command('foo')
  .action(function(args, callback) {
    
    // This will properly log to your terminal.
    this.log('bar');

    // This will create problems.
    console.log('bar'); 

    callback();
  });

commandInstance.prompt(object[, callback])

Vorpal supports mid-command prompting. You can make full use of Inquirer.js's prompt method, which is exposed through this.prompt.

vorpal.command('destroy database')
  .action(function(args, cb){
    const self = this;
    return this.prompt({
      type: 'confirm',
      name: 'continue',
      default: false,
      message: 'That sounds like a really bad idea. Continue?',
    }, function(result){
      if (!result.continue) {
        self.log('Good move.');
        cb();
      } else {
        self.log('Time to dust off that resume.');
        app.destroyDatabase(cb);
      }
    });
  });
dbsvr~$ destroy database
? That sounds like a really bad idea. Continue? y/N: N
Good move.
dbsvr~$

This includes support for all Inquirer prompt types.

commandInstance.delimiter(string)

Change the prompt delimiter mid command. At the end of the command, this will reset to the delimiter assigned through vorpal.delimiter().

vorpal
  .command('delimiter <string>')
  .action(function(args, cb){
    this.delimiter(args.string);
    cb();
  });
websvr~$ delimiter unicornsvr~$
unicornsvr~$
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.