从控制台以交互方式读取值


155

我想做一个带有控制台扩展的简单服务器http服务器。我找到了要从命令行数据读取的代码段。

  var i = rl.createInterface(process.stdin, process.stdout, null);
  i.question('Write your name: ', function(answer) {
    console.log('Nice to meet you> ' + answer);
    i.close();
    process.stdin.destroy();

  });

好再问一次问题,我不能简单地使用while(done) { }循环?如果服务器在询问时间接收到输出,也会破坏线路。


5
我以rl您的意思假设是热线
jpaugh

您可以使用非阻塞接口(如此答案中使用的接口),然后可以进行while(done)循环。
Keyvan

Answers:


182

您无法执行“ while(done)”循环,因为这将需要阻止输入,而node.js则不喜欢这样做。

而是设置一个在每次输入内容时都要调用的回调:

var stdin = process.openStdin();

stdin.addListener("data", function(d) {
    // note:  d is an object, and when converted to a string it will
    // end with a linefeed.  so we (rather crudely) account for that  
    // with toString() and then trim() 
    console.log("you entered: [" + 
        d.toString().trim() + "]");
  });

2
谢谢您的这项工作,“ end”侦听器是否可以调用一些关闭操作并说'再见'?
Risto Novik

我从示例中删除了“结束”侦听器,但我不知道说实话在什么地方真正有用。

2
您可以将字符串输出简化为d.toString()。trim()
MKN Web Solutions

6
该答案的日期为2011年,此后发生了很大变化。尤其是答案的第一部分,您无法进行while循环...不再成立。是的,由于async-await模式,您可以进行while循环,但仍然不会阻塞。其他答案反映了这一点。对于当今阅读此书的任何人-也请参考其他答案。
维克多·齐克拉

1
要继续使用@WiktorZychla,该函数process.openStdin在仍在运行时于2011年左右弃用,您将找不到有关它的任何文档。
calder.ty

111

我为此使用了另一个API。

var readline = require('readline');
var rl = readline.createInterface(process.stdin, process.stdout);
rl.setPrompt('guess> ');
rl.prompt();
rl.on('line', function(line) {
    if (line === "right") rl.close();
    rl.prompt();
}).on('close',function(){
    process.exit(0);
});

这样可以循环提示直到答案为right。它还提供了一个不错的控制台。您可以在@ http://nodejs.org/api/readline.html#readline_example_tiny_cli中找到详细信息


11
这是一个很好的答案。可能不明显(但很大的优点)的是,readline不是外部依赖项:它是node.js的一部分。
jlh

51

自12英尺以来,Readline API发生了很大变化。该文档显示了一个有用的示例,可以从标准流中捕获用户输入:

const readline = require('readline');

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

rl.question('What do you think of Node.js? ', (answer) => {
  console.log('Thank you for your valuable feedback:', answer);
  rl.close();
});

更多信息在这里。


5
这只是一个基本示例。您如何互动?问题/答案?多个选择之类的?一旦关闭,如何重新打开rl,如果不能使用open rl与用户互动,包括一些逻辑
Pawel Cioch

27

我相信async-await,如果使用节点> = 7.x,这应该得到一个现代的答案。

答案仍然使用ReadLine::question但将其包装以使成为while (done) {}可能,这是OP明确要求的。

var cl = readln.createInterface( process.stdin, process.stdout );
var question = function(q) {
    return new Promise( (res, rej) => {
        cl.question( q, answer => {
            res(answer);
        })
    });
};

然后是一个示例用法

(async function main() {
    var answer;
    while ( answer != 'yes' ) {
        answer = await question('Are you sure? ');
    }
    console.log( 'finally you are sure!');
})();

导致后续对话

Are you sure? no
Are you sure? no
Are you sure? yes
finally you are sure!

这正是我一直在寻找的答案。我认为它应该是头号。
威廉·周

美丽。较大的脚本需要异步等待。这正是我所需要的。
Abhay Shiro

25

请使用readline-sync,这使您可以使用同步控制台而不会发生回调。甚至可以使用密码:

var favFood = read.question('What is your favorite food? ', {
  hideEchoBack: true // The typed text on screen is hidden by `*` (default). 
});


5
这需要额外的依赖关系,因此我希望使用其他解决方案。
Risto Novik

无法在SO上运行“ Uncaught ReferenceError:未定义读取”
awwsmm

12

@rob答案在大多数情况下都会起作用,但是对于长输入,它可能无法按预期工作。

那就是您应该使用的:

const stdin = process.openStdin();
let content = '';

stdin.addListener('data', d => {
  content += d.toString();
});

stdin.addListener('end', () => {
  console.info(`Input: ${content}`);
});

有关此解决方案为何有效的解释:

addListener('data') 就像缓冲区一样,当回调已满或/和输入结束时将调用回调。

那么长输入呢?仅有一个'data'回调是不够的,因此您会将输入分为两部分或更多部分。这通常不方便。

addListener('end')标准输入法阅读器阅读完输入内容后,将通知我们。由于我们一直在存储先前的数据,因此我们现在可以一起读取和处理所有数据。


3
当我使用上面的代码并插入一些输入,然后按“ Enter”键时,控制台不断询问我更多的输入。我们应该如何终止它?
马坦·图布尔

5

我建议使用Inquirer,因为它提供了常见的交互式命令行用户界面的集合。

const inquirer = require('inquirer');

const questions = [{
  type: 'input',
  name: 'name',
  message: "What's your name?",
}];

const answers = await inquirer.prompt(questions);
console.log(answers);

5

这是一个例子:

const stdin = process.openStdin()

process.stdout.write('Enter name: ')

stdin.addListener('data', text => {
  const name = text.toString().trim()
  console.log('Your name is: ' + name)

  stdin.pause() // stop reading
})

输出:

Enter name: bob
Your name is: bob

兄弟回答不错!简单明了。
MD.JULHAS HOSSAIN'July

3

这太复杂了。一个更简单的版本:

var rl = require('readline');
rl.createInterface... etc

将使用

var rl = require('readline-sync');

然后它将在您使用时等待

rl.question('string');

那么它更容易重复。例如:

var rl = require('readline-sync');
for(let i=0;i<10;i++) {
    var ans = rl.question('What\'s your favourite food?');
    console.log('I like '+ans+' too!');
}

2

一个常见的用例可能是应用程序显示通用提示并在switch语句中进行处理。

通过使用将在回调中自行调用的辅助函数,您可以获得与while循环等效的行为:

const readline = require('readline');
const rl = readline.createInterface(process.stdin, process.stdout);

function promptInput (prompt, handler)
{
    rl.question(prompt, input =>
    {
        if (handler(input) !== false)
        {
            promptInput(prompt, handler);
        }
        else
        {
            rl.close();
        }
    });
}

promptInput('app> ', input =>
{
    switch (input)
    {
        case 'my command':
            // handle this command
            break;
        case 'exit':
            console.log('Bye!');
            return false;
    }
});

您可以传递一个空字符串,而不是'app> '如果您的应用已在此循环之外在屏幕上打印了一些内容。


2

我的解决方法是使用异步生成器

假设您有一系列问题:

 const questions = [
        "How are you today ?",
        "What are you working on ?",
        "What do you think of async generators ?",
    ]

为了使用await关键字,您必须将程序包装到异步IIFE中。

(async () => {

    questions[Symbol.asyncIterator] = async function * () {
        const stdin = process.openStdin()

        for (const q of this) {
            // The promise won't be solved until you type something
            const res = await new Promise((resolve, reject) => {
                console.log(q)

                stdin.addListener('data', data => {
                    resolve(data.toString())
                    reject('err')
                });
            })

            yield [q, res];
        }

    };

    for await (const res of questions) {
        console.log(res)
    }

    process.exit(0)
})();

预期成绩:

How are you today ?
good
[ 'How are you today ?', 'good\n' ]
What are you working on ?
:)
[ 'What are you working on ?', ':)\n' ]
What do you think about async generators ?
awesome
[ 'What do you think about async generators ?', 'awesome\n' ]

如果您想完全回答问题,可以通过简单的修改来实现:

const questionsAndAnswers = [];

    for await (const res of questions) {
        // console.log(res)
        questionsAndAnswers.push(res)
    }

    console.log(questionsAndAnswers)

   /*
     [ [ 'How are you today ?', 'good\n' ],
     [ 'What are you working on ?', ':)\n' ],
     [ 'What do you think about async generators ?', 'awesome\n' ] ]
   */

2

我必须在Node中编写一个“井字游戏”,该游戏从命令行获取输入,并编写了完成该操作的基本async / await代码块。

const readline = require('readline')

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

async function getAnswer (prompt) {
  const answer = await new Promise((resolve, reject) =>{
    rl.question(`${prompt}\n`, (answer) => {
      resolve(answer)
    });
  })
  return answer
}

let done = false
const playGame = async () => {
  let i = 1
  let prompt = `Question #${i}, enter "q" to quit`
  while (!done) {
    i += 1
    const answer = await getAnswer(prompt)
    console.log(`${answer}`)
    prompt = processAnswer(answer, i)
  }
  rl.close()
}

const processAnswer = (answer, i) => {
  // this will be set depending on the answer
  let prompt = `Question #${i}, enter "q" to quit`
  // if answer === 'q', then quit
  if (answer === 'q') {
    console.log('User entered q to quit')
    done = true
    return
  }
  // parse answer

  // if answer is invalid, return new prompt to reenter

  // if answer is valid, process next move

  // create next prompt
  return prompt
}

playGame()

1

阻止readline畅行无阻

想象一下,您有三个问题要从控制台中回答,因为您现在知道该代码将不会运行,因为readline标准模块具有“不受阻碍”的行为,即每个rl.question是一个独立线程,因此该代码将不会运行。

'use strict';

var questionaire=[['First Question: ',''],['Second Question: ',''],['Third Question: ','']];

function askaquestion(question) {
const readline = require('readline');

const rl = readline.createInterface(
    {input: process.stdin, output:process.stdout}
    );
  rl.question(question[0], function(answer) {
    console.log(answer);
    question[1] = answer;
    rl.close();
  });
};

var i=0;  
for (i=0; i < questionaire.length; i++) {
askaquestion(questionaire[i]);
}

console.log('Results:',questionaire );

运行输出:

node test.js
Third Question: Results: [ [ 'First Question: ', '' ],
  [ 'Second Question: ', '' ],
  [ 'Third Question: ', '' ] ]        <--- the last question remain unoverwritten and then the final line of the program is shown as the threads were running waiting for answers (see below)
aaa        <--- I responded with a single 'a' that was sweeped by 3 running threads
a        <--- Response of one thread

a        <--- Response of another thread

a        <--- Response of another thread (there is no order on threads exit)

所提出的解决方案使用事件发射器来发信号通知未阻塞线程的结束,并将循环逻辑和程序结束包括在其侦听器函数中。

'use strict';

var questionaire=[['First Question: ',''],['Second Question: ',''],['Third Question: ','']];

// Introduce EventEmitter object
const EventEmitter = require('events');

class MyEmitter extends EventEmitter {};

const myEmitter = new MyEmitter();
myEmitter.on('continue', () => {
  console.log('continue...');
  i++; if (i< questionaire.length) askaquestion(questionaire[i],myEmitter);    // add here relevant loop logic
           else console.log('end of loop!\nResults:',questionaire );
});
//

function askaquestion(p_question,p_my_Emitter) { // add a parameter to include my_Emitter
const readline = require('readline');

const rl = readline.createInterface(
    {input: process.stdin, output:process.stdout}
    );
  rl.question(p_question[0], function(answer) {
    console.log(answer);
    p_question[1] = answer;
    rl.close();
    myEmitter.emit('continue');    // Emit 'continue' event after the question was responded (detect end of unblocking thread)
  });
};

/*var i=0;  
for (i=0; i < questionaire.length; i++) {
askaquestion(questionaire[i],myEmitter);
}*/

var i=0;
askaquestion(questionaire[0],myEmitter);        // entry point to the blocking loop


// console.log('Results:',questionaire )    <- moved to the truly end of the program

运行输出:

node test2.js
First Question: 1
1
continue...
Second Question: 2
2
continue...
Third Question: 3
3
continue...
done!
Results: [ [ 'First Question: ', '1' ],
  [ 'Second Question: ', '2' ],
  [ 'Third Question: ', '3' ] ]

0

我已经创建了一个小脚本来读取目录,并将控制台名称新文件(例如:'name.txt')写入文本。

const readline = require('readline');
const fs = require('fs');

const pathFile = fs.readdirSync('.');

const file = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

file.question('Insert name of your file? ', (f) => {
  console.log('File is: ',f.toString().trim());
  try{
    file.question('Insert text of your file? ', (d) => {
      console.log('Text is: ',d.toString().trim());
      try {
        if(f != ''){
          if (fs.existsSync(f)) {
            //file exists
            console.log('file exist');
            return file.close();
          }else{
            //save file
            fs.writeFile(f, d, (err) => {
                if (err) throw err;
                console.log('The file has been saved!');
                file.close();
            });
          }
        }else{
          //file empty 
          console.log('Not file is created!');
          console.log(pathFile);
          file.close();
        }
      } catch(err) {
        console.error(err);
        file.close();
      }
    });
  }catch(err){
    console.log(err);
    file.close();
  }
});

0

最简单的方法是使用readline-sync

它一一处理输入和输出。

npm i readline-sync

例如:

var firstPrompt = readlineSync.question('Are you sure want to initialize new db? This will drop whole database and create new one, Enter: (yes/no) ');

if (firstPrompt === 'yes') {
    console.log('--firstPrompt--', firstPrompt)
    startProcess()
} else if (firstPrompt === 'no') {
    var secondPrompt = readlineSync.question('Do you want to modify migration?, Enter: (yes/no) ');
    console.log('secondPrompt ', secondPrompt)
    startAnother()
} else {
    console.log('Invalid Input')
    process.exit(0)
}

您确实应该包括您的require声明。没有理由将其遗漏。
solidstatejake
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.