Search code examples
node.jshttpexpressstreaming

What is the advantage of using pipe function over res.write


The framework is Express.

When I'm sending a request from within an end point and start receiving data, either I can read data in chunks and write them instantly:

responseHandler.on('data', (chunk) => {
  res.write(chunk);
});

Or I can create a writable stream and pipe the response to that.

responseHandler.pipe(res)

It is obvious that the pipe function takes care of the former process with more dimensions to it. What are they?


Solution

  • The most important difference between managing event handlers and using readable.pipe(writable) is that using pipe:

    The flow of data will be automatically managed so that the destination Writable stream is not overwhelmed by a faster Readable stream. Pipe

    It means that readable stream may be faster than writable and pipe handles that logic. If you are writing code like:

        responseHandler.on('data', (chunk) => {
            res.write(chunk);
        });
    

    res.write() function

    Returns: (boolean) false if the stream wishes for the calling code to wait for the 'drain' event to be emitted before continuing to write additional data; otherwise true. Link

    It means that writable stream could be not ready to handle more data. So you can manage this manually as mentioned in writable.write() example.

    In some cases you do not have readable stream and you could write to writable stream using writable.write(). Example

        const data = []; // array of some data.
        data.forEach((d) => writable.write(d));
    

    But again, you must see what writable.write returns. If it is false you must act in a manual fashion to adjust stream flow.

    Another way is to wrap your data into readable stream and just pipe it.

    By the way, there is one more great advantage of using pipes. You can chain them by your needs, for instance:

        readableStream
            .pipe(modify)      // transform stream
            .pipe(zip)         // transform stream
            .pipe(writableStream);
    

    By summing everything up piggyback on node.js given functionality to manage streams if possible. In most cases it will help you avoid extra complexity and it will not be slower compared to managing it manually.