关于node.js:Node的Commander无法提示终端

Node's Commander can't prompt terminal

我正在构建的命令行程序中使用流行的Commander npm模块。 除了提供的所有功能(要求用户输入,又名,选择,提示和密码)无法正常工作外,它的工作原理非常好。

作为示例,我正在使用:

1
2
3
4
5
6
7
8
9
10
11
12
program
    .command('test')
    .action(function(param) {
        program.prompt('Username: ', function(name){
          console.log('hi %s', name);
        });

        program.prompt('Description:', function(desc){
          console.log('description was"%s"', desc.trim());
        });
    }
);

这将导致以下错误(但仍被复制并直接粘贴到文档/示例之外):

TypeError: Object # has no method 'prompt'
at Command. (lib/tg.js:780:11)
at Command.listener (node_modules/commander/index.js:249:8)
at Command.emit (events.js:98:17)
at Command.parseArgs (/node_modules/commander/index.js:480:12)
at Command.parse (/node_modules/commander/index.js:372:21)
at Object. (/lib/tg.js:806:9)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)


尝试使用节点提示模块。 使用以下命令从npm安装它:

npm install prompt --save

该文档可以在这里找到:https://github.com/flatiron/prompt

确保在代码中也通常在顶部都要求它。

var prompt = require('prompt');

请记住,Node是非阻塞的。 多个提示将尝试同时获取用户输入。 要解决此问题,请将您的提示分成多个函数,然后在回调中调用下一个提示。

例:

1
2
3
4
5
6
7
8
9
10
11
12
var first_prompt = function() {
  var schema = {
    // Read the docs on creating a prompt schema
  };
  prompt.start();
  prompt.get(schema, function(err, result) {
    // Do stuff with the input

    // Call the next prompt
    next_prompt();
  });
};