Jackson Ray Hamilton
Jackson Ray Hamilton

Reputation: 9466

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.

Upvotes: 0

Views: 310

Answers (1)

Jackson Ray Hamilton
Jackson Ray Hamilton

Reputation: 9466

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;
};

Upvotes: 1

Related Questions