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

问题描述 投票:1回答:1

从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> 

并立即退出,永远不会等待提示。

Yum on Vindovs,Node vv.2.1

node.js stdin prompt node.js-stream
1个回答
0
投票

就像@AlexeyTen在比较中所说,使用ttys包或类似的使用tty,用于需要来自控制台的输入。

var ttys = require('ttys');
const rl = readline.createInterface({
    input: ttys.stdin,
    output: ttys.stdout
});
© www.soinside.com 2019 - 2024. All rights reserved.