nodejsstream与callback

我阅读这篇文章: http : //elegantcode.com/2011/04/06/taking-baby-steps-with-node-js-pumping-data-between-streams/和理解stream有一些轻微的麻烦。

引用:

"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." 

所以代码示例如下:

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

为什么我们可以简单地使用上面的方法:

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

何时或为什么要使用stream?

处理大文件时,您会使用stream。 通过callback,所有文件的内容必须一次加载到内存中,而在一个stream中,在任何给定的时间只有一个文件块在内存中。

此外,stream接口可以说是更优雅。 而不是显式附加datadrainendcallback,你可以改为使用pipe

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

一个重要的原因是你可以在数据全部在内存之前开始处理数据。 想一想“stream媒体video”,在那里你可以开始观看剪辑,而它仍然在加载。 在许多使用情况下,stream将允许您在加载完整内容之前开始处理文件中的数据。

另一个常见的用例是当你只想读取一个对象直到你检测到数据中的某个条件。 假设您需要检查一个大文件是否包含单词“rabbit”。 如果使用callback模式,则需要将整个文件读入内存,然后检查文件并检查单词是否在里面。 有了stream,你可能会检测到文件第5行的单词,那么你可以closuresstream,而不用加载整个事情。

显然有更复杂的用例,并且仍然有很多时候,为了简单起见,callback仍然更有意义(例如,如果您需要计算“兔子”出现的总次数,在这种情况下,您必须加载整个文件无论如何)。