Why use streams?

Presented with a fancy new language feature, design pattern, or software module, a novice developer may begin using it because it is new and fancy. An experienced developer, on the other hand, might ask, why is this required?

Streams are required because files are big. A few simple examples can demonstrate their necessity. To begin, let's say we want to copy a file. In Node, a naive implementation looks like this:

// First attemptconsole.log('Copying...');let block = fs.readFileSync("source.bin");console.log('Size: ' + block.length);fs.writeFileSync("destination.bin", block);console.log('Done.');

It's very straightforward.

The call to readFileSync() blocks while Node copies the contents of source.bin, a file in the same folder ...

Get Mastering Node.js - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.