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 attempt console.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 as the script, into memory, returning a ByteBuffer
here named block
.
Once we have block
, we can check and print out its size. Then, the code hands block
to writeFileSync
, which copies the memory block to the contents of a newly made or overwritten...