Search code examples
javascriptnode.jscommand-line-tool

Commander.js : script not waiting for user input


I am just starting to use node.js and commander.js so it might be a stupid question...

So I am trying to make a command line tool where I need to ask some info to the user. I am trying to use commander.js as it seems simple. The problem is that when I run the script, it doesn't wait for the user to type the answers, and execute all the script. How can I make this work?

Here is how i organized my code:

#!/usr/bin/env node

var program = require('commander');

program
    .version('0.0.1')
    .option('-c, --create', 'Create new stuff')
    .parse(process.argv);

if(program.create){
    console.log('Creating new stuff');

    program.prompt('Name of the stuff: ', function(name){
        var stuffName = name;
    });

    program.prompt('Description of the stuff: ', function(description){
        var stuffDescription = description;
    });
} 

Thanks


Solution

  • You have to put the second prompt inside the callback from the first one.

    program.prompt('Name of the stuff: ', function(name){
        var stuffName = name;
        program.prompt('Description of the stuff: ', function(description){
            var stuffDescription = description;
        });
    
    });
    

    If you don't do that, then both prompts are printed out right away; the API is asynchronous.