Nodejs streams vs callbacks

I read this article: http://elegantcode.com/2011/04/06/taking-baby-steps-with-node-js-pumping-data-between-streams/ and with minor problems understand the flows.

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, an example code looks like this:

var readStream = fileSystem.createReadStream(filePath);
readStream.on('data', function(data) {
    response.write(data);
});

readStream.on('end', function() {
    response.end();        
});

Why could we use this above when we could just do:

fs.readFile(filePath, function(err, data){
  response.write(data);
  response.end();
});

When or why use streams?

+5
source share
2 answers

You use a stream when working with large files. With a callback, the entire contents of the file must be loaded into memory immediately, and with a stream at any moment in time there will be only a fragment of the file in memory.

, , , . data, drain end pipe:

var readStream = fileSystem.createReadStream(filePath);
readStream.pipe(response);
+13

, , . " ", , - . , .

- , - . , , "". , , , . 5 , , .

, , , , (, "", ).

+5

All Articles