2014-09-02 46 views
0

我在我正在建立的命令行程序中使用流行的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: 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)

回答

2

使用嘗試節點提示模塊。從NPM使用此命令來安裝它:

npm install prompt --save

的文檔可以在這裏找到:https://github.com/flatiron/prompt

請確保您還要求它在你的代碼,通常是在頂部。

var prompt = require('prompt');

記住,節點是非阻塞的。多個提示將嘗試同時獲取用戶輸入。爲了解決這個問題,將你的提示分解成函數並在回調中調用下一個提示。

實施例:

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