节点的指挥官不能提示终端

时间:2014-09-02 22:50:53

标签: node.js

我在我正在构建的命令行程序中使用了流行的Commander npm模块。它的效果很好,除了它提供的所有要求用户输入的功能 - 也就是选择,提示和密码 - 都无法正常工作。

我正在使用的例子:

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:对象#没有方法'提示'       在命令。 (LIB / tg.js:780:11)       在Command.listener(node_modules / commander / index.js:249:8)       在Command.emit(events.js:98:17)       在Command.parseArgs(/node_modules/commander/index.js:480:12)       在Command.parse(/node_modules/commander/index.js:372:21)       在对象。 (/lib/tg.js:806:9)       在Module._compile(module.js:456:26)       at Object.Module._extensions..js(module.js:474:10)       在Module.load(module.js:356:32)       在Function.Module._load(module.js:312:12)

1 个答案:

答案 0 :(得分:2)

尝试使用Node Prompt模块。使用以下命令从npm安装它:

npm install prompt --save

可在此处找到文档:https://github.com/flatiron/prompt

请确保您的代码中也需要它,通常位于顶部。

var prompt = require('prompt');

请记住,Node是非阻塞的。多个提示将尝试同时获得用户输入。要解决此问题,请将提示拆分为函数并调用回调中的下一个提示。

示例:

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();
  });
};