最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

运维笔记admin13浏览0评论

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

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

从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

回答如下:

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

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

评论列表(0)

  1. 暂无评论