Im reading this article: http://elegantcode.com/2011/04/06/taking-baby-steps-with-node-js-pumping-data-between-streams/ and having some slight troubles understanding streams.
Quote:
"Suppose we want to develop a simple web application that reads a particular file from disk and send it to the browser. The following code shows a very simple and naïve implementation in order to make this happen."
So the code sample is as follows:
var readStream = fileSystem.createReadStream(filePath);
readStream.on('data', function(data) {
response.write(data);
});
readStream.on('end', function() {
response.end();
});
Why would we use that above way when we could simply do:
fs.readFile(filePath, function(err, data){
response.write(data);
response.end();
});
When or why would I use streams?
You’d use stream when working with large files. With a callback, all of the file’s contents must be loaded into memory at once, while with a stream, only a chunk of the file is in memory at any given time.
Also, the stream interface is arguably more elegant. Instead of explicitly attaching
data,drain, andendcallbacks, you can instead usepipe: