Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
919 views
in Technique[技术] by (71.8m points)

为什么 process.stdin 会有 write 方法? ???

写在前面

根据 官方API,在 stream 中只有可写流才会有 write 方法,但是有这样一个例子却使用
process.stdin.write() 发送数据。而 process.stdin 在 官方API 中是可读流。

问题:

RT,如果是其他的原因造成这样一个情况,麻烦详细描述一下。谢谢

参考代码:

stdin.js

/**
 * 监听输入的数据,并输出到控制台
 */
// 重新开始 stdin stream
process.stdin.resume();
// 监听输入的数据
process.stdin.on('data', function (data) {
  var number;
  try {
    // 将输入的信息解析成数字
    number = parseInt(data.toString(), 10);
    // 自增1
    number += 1;
    // 输出 数字
    process.stdout.write(number + "
",function() {
      console.log(1);
    });
  } catch (err) {
    process.stderr.write(err.message + "
");
  }
});

stdin_test.js

var spawn = require('child_process').spawn;

// 使用 node 进程创建一个子进程执行 stdin.js
var child = spawn('node', ['stdin.js']);

// 每隔一秒调用一次该函数
setInterval(function() {

  // 生成一个小于 10 的随机数
  var number = Math.floor(Math.random() * 10);

  // 将该随机数发送到子进程
  child.stdin.write(number + "
");

  // 监听子进程的输出 并打印出来
  //   此处对应 stdin.js 的 process.stdout.write
  child.stdout.once('data', function(data) {
    console.log('child replied to ' + number + ' with: ' + data);
  });
}, 1000);

child.stderr.on('data', function(data) {
  process.stdout.write(data);
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

注意这里的 stdin 是 ChildProcess 的,是可写流

https://nodejs.org/dist/lates...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...