简体   繁体   中英

Create “intermediate” stream in Node.js

What is the best way to create an "intermediate" stream in Node.js? That is, a stream which just gathers information from another stream and pipes it out.

For instance, I might want to return a stream immediately from a function with asynchronous flow:

var streamingQuery = function (query) {
    var intermediateStream = new IntermediateStream();
    database.connect(function (client) {
        var queryStream = client.query(query);
        queryStream.pipe(intermediateStream);
    });
    return intermediateStream;
};

I think stream.DuplexStream might be what I need, but I'm not sure the best way of making that type of stream just pass all its data along to the next stream. Or maybe there is a handy helper function for accomplishing this particular task, and if so I'd like to know about it.

I discovered that stream.PassThrough is built-in and seems to do what I want.

var stream = require('stream');
var streamingQuery = function (query) {
    var intermediateStream = new stream.PassThrough();
    database.connect(function (client) {
        var queryStream = client.query(query);
        queryStream.pipe(intermediateStream);
    });
    return intermediateStream;
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM