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 O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.