WeCodeAcademy

Node.js Streams

A stream processes data in chunks instead of loading it all at once. This matters for big files and network data.

ExampleNode.js
const { Readable, Transform, Writable } = require("stream");
const { pipeline } = require("stream/promises");

const source = Readable.from(["alpha ", "beta ", "gamma"]);
const upper = new Transform({
  transform(chunk, enc, cb) {
    cb(null, chunk.toString().toUpperCase());
  },
});
const parts = [];
const sink = new Writable({
  write(chunk, enc, cb) {
    parts.push(chunk.toString());
    cb();
  },
});

pipeline(source, upper, sink).then(() => {
  console.log(parts);
  console.log(parts.join(""));
});
Output
[ 'ALPHA ', 'BETA ', 'GAMMA' ]
ALPHA BETA GAMMA
Quick check

Why use streams for large files?

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.