Chain Data Streams in Node.js

Node.js·2 min read·Jan 1, 2025

Piping is a mechanism that connects a readable stream to a writable stream, allowing data to flow directly between them without manual handling of the data chunks.

This is particularly useful for tasks like reading from a file and writing to another file, or streaming data over the network.

To pipe streams, you can use the pipe() method of the readable stream instance:

readable.pipe(writable);

Example

Let's consider this file named original.txt located in the current directory:

$ cat original.txtLorem ipsum dolor sit amet, consectetur adipiscing elit.Aliquam at ullamcorper magna, non tempus neque.Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.

Let's consider this script, that copies a file using the piping mechanism:

const fs = require('node:fs');const source = fs.createReadStream('original.txt', {  encoding: 'utf8'});

Unlock the program 🚀

Pay once, own it forever.

€79

30-day money-back guarantee

  • 13 modules
  • 113 lessons with full-code examples
  • 29 projects with commented solutions
  • All future lesson and project updates
  • Lifetime access

By submitting this form, you agree to the Terms & Conditions and Privacy Policy.