javascriptnode.jsvorpal.js

Vorpal.js parameters and arguments


I'm developing a Node.js app and I'm using Vorpal commands. I'm trying to send a value from the command to a function but i can't get it to work. Am I doing anything wrong?

Here is the code:

vorpal
  .command('rollto <num>', 'Rolls to')
  .action(function(num) {
    rollto(num);
  }); 

function rollto(num) {
    bettime = bettimems % 60;
    socket.emit('betting', bettime);
    timer1 = setInterval(function () {
        bettime--;
        socket.emit('betting', bettime);

        if (bettime == 0) {
            socket.emit('random number', num);     
            console.log("Rolled to:" + num + "!!!");
            clearInterval(timer1);
        }
    }, 1000); 
}

Solution

  • The problem is that the function you pass to command's action has different arguments than you assume.

    Here is the relevant part from docs:

    .command.action(function)
    
    This is the action execution function of a given command. 
    It passes in an arguments object and callback.
    
    Actions are executed async and must either call the passed 
    callback upon completion or return a Promise.
    

    And here is a working example:

    var vorpal = require('vorpal')();
    
    vorpal
    .command('rollto <num>', 'Rolls to')
    .action(function(arguments, callback) {
        rollto(arguments, callback);
    });
    
    function rollto(arguments, callback) {
        var num = arguments.num;  // get 'num' parameter from arguments
        timer1 = setInterval(function () {
            console.log('test');
            console.log(num);
            clearInterval(timer1);
            callback();  // Don't forget to use callback() to notify vorpal
        }, 1000);
    }
    
    vorpal
      .delimiter('myapp$')
      .show();
    

    Note that you actually have an async code inside setInterval, so you need to use callback() at the end to notify vorpal that processing is finished.