javascript - 为什么 process.stdin 会有 write 方法◔ ‸◔?

查看:95
本文介绍了javascript - 为什么 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 + "\n",function() {
      console.log(1);
    });
  } catch (err) {
    process.stderr.write(err.message + "\n");
  }
});

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 + "\n");

  // 监听子进程的输出 并打印出来
  //   此处对应 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);
});

解决方案

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

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

这篇关于javascript - 为什么 process.stdin 会有 write 方法◔ ‸◔?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆