Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/34.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js如何在从shell管道读取后使用stdin流读取用户输入_Node.js_Stdin_Prompt_Node.js Stream - Fatal编程技术网

Node.js如何在从shell管道读取后使用stdin流读取用户输入

Node.js如何在从shell管道读取后使用stdin流读取用户输入,node.js,stdin,prompt,node.js-stream,Node.js,Stdin,Prompt,Node.js Stream,从shell管道接收数据后,我需要通过提示符询问用户。但从管道中读取数据后,应用程序立即关闭。热到让它等待用户输入 var readline = require('readline'); var data = ''; process.stdin.setEncoding('utf8'); process.stdin.on('readable', function() { var chunk = process.stdin.read(); if (chunk !== null) {

从shell管道接收数据后,我需要通过提示符询问用户。但从管道中读取数据后,应用程序立即关闭。热到让它等待用户输入

var readline = require('readline');

var data = '';
process.stdin.setEncoding('utf8');
process.stdin.on('readable', function() {
  var chunk = process.stdin.read();
  if (chunk !== null) {
    data+=chunk;                
  }
}); 

process.stdin.on('end', function() {

  console.log('from pipe: ' + data);

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

  rl.question('prompt> ', (answer) => {
    console.log('from prompt: ', answer);
    rl.close();
  });
});
当我运行这个脚本时

$ echo "pipe" | node app.js
它打印

from pipe: pipe

prompt> 
并立即退出,从不等待提示


我在Windows上,节点v4.2.1

就像@AlexeyTen在Commos中说的那样,对于需要从控制台输入的内容,使用包或使用tty的类似程序

var ttys = require('ttys');
const rl = readline.createInterface({
    input: ttys.stdin,
    output: ttys.stdout
});

在摩卡咖啡压制stdin的时候,这些解决方案对我都不起作用。相反,我用


您正在调用问题中的
rl.close()
,因此问题结束。删除它并仅在实际完成时关闭它。看起来节点线程不等待事件处理程序。@aug
rl.close()
实际上没有被调用。代码执行不会进入question回调。@S.D.但它会等待超时:如果我用readline替换操纵,用setTimeout(函数(){console.log('waited');},1000)当您使用管道时,它将打印出“等待”,这是一个标准输入。阅读完所有的标准后,你想使用TTY吗
function promptToContinue()
{  
   const readlineSync = require('readline-sync');

   if (readlineSync.keyInYN("WARNING this will destroy your file.\n Press [Y/n] to continue> " ))
   {
      // User pressed Y or y
      return;
   } else {
      process.exit(-1);
   }
}