单流多次消费 [英] Multiple Consumption of single stream

查看:102
本文介绍了单流多次消费的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有可能多个功能可以消耗node.js中的单个流.如果是,怎么办?是否可以通过管道传输到多个目的地?

I want to know if its possible that multiple functions can consume single stream in node.js. If yes How can this done? Is it possible to pipe to multiple destinations?

我想在两个并行的不同函数中使用流.我正在使用异步模块进行并行流.那么是否可以说在这些函数中的每个函数中发出pipe()语句?

I want to use the stream in two different functions which are parallel. I am doing the parallel flow using the async module. So will it possible to say issue the pipe() statement inside each of these functions?

谢谢.

推荐答案

,这是可能的,容易的和常见的.以下是从单个源到多个源的管道数据流.它向您展示了一个放置在事件循环中的匿名回调函数,该函数包含执行实际写入工作的写入函数流:

Yes, it's possible, easy and common. The following is a piped data stream from a single source to multiple sources. It shows you the one anonymous callback function that gets placed on the event loop that contains the write function streams that do the actual write work:

var fs  = require('fs');

var rs1 = fs.createReadStream ('input1.txt');                      
var ws1 = fs.createWriteStream('output1.txt');     
var ws2 = fs.createWriteStream('output2.txt');

rs1.on('data', function (data) {                                  
  console.log(data.toString('utf8'));                              
  ws1.write('1: ' + data);                                       
  ws2.write('2: ' + data);                                       
});

一种更简单的方法是使用.pipe()函数.

An easier way is to use the .pipe() functions.

var fs  = require('fs');

var rs1 = fs.createReadStream ('input1.txt');                      
var ws1 = fs.createWriteStream('output1.txt');     
var ws2 = fs.createWriteStream('output2.txt');

rs1.pipe(ws1);
rs1.pipe(ws2);

.pipe()允许您将来做一些漂亮的事情,例如管道链接以进行管道操作,这与du . | sort -rn | less之类的unix概念非常相似,在其中您可以使用多个管道进行处理.

The .pipe() allows you to do nifty things like pipeline chaining in the future for pipeline manipulation, very similar to the unix concept of something like du . | sort -rn | less where you can use multiple pipes to handlers.

这篇关于单流多次消费的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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