在nodejs中同步接受命令行input的最佳方法是什么?

在nodejs中同步接受一系列命令行input的最好方法是什么?

像程序将打印

Enter Value for variable one 

然后用户input值,之后命令行应该要求第二个input

 Enter Value for variable two 

等等

要做到这一点,最简单的方法,恕我直言是向用户显示“问题”,并等待他的答案。 这些问题可以总是相同的(像“>>”这样的提示)或者可能不同(例如,如果你想要求一些variables)。

要显示这些问题,您可以使用stdio 。 它是一个简化标准input/输出pipe理的模块,其主要function之一正是您想要的:

 var stdio = require('stdio'); stdio.question('What is your name?', function (err, name) { stdio.question('Are you male or female?', ['male', 'female'], function (err, sex) { console.log('Your name is "%s". You are "%s"', name, sex); }); }); 

如果你运行以前的代码,你会看到这样的东西:

 What is your name?: John Are you male or female? [male/female]: female Your name is "john". You are "female" 

如果您指定了一组可能的答案, stdio包括对重试的支持。 否则用户将能够写任何他们想要的。

PD:我是stdio创造者。 🙂

NPM

根据您的具体需求,您可以创build自己的REPL。

http://nodejs.org/api/repl.html

只需调用repl.start() prompt选项,并使用自己的自定义evalrepl.start()callback。

 repl.start({ prompt: 'Enter value: ', eval: function (cmd, context, filename, callback) { // Do something callback(/* return value goes here */); }, writer: function (data) { // echo out data to the console here } });