6

我正在阅读这篇文章:http ://elegantcode.com/2011/04/06/taking-baby-steps-with-node-js-pumping-data-between-streams/并且在理解流时遇到了一些小麻烦。

引用:

"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();
});

我何时或为什么要使用流?

4

2 回答 2

15

处理大文件时,您会使用流。使用回调,所有文件的内容必须一次加载到内存中,而使用流,在任何给定时间只有文件的一部分在内存中。

此外,流接口可以说更优雅。除了显式附加datadrainend回调之外,您还可以使用pipe

var readStream = fileSystem.createReadStream(filePath);
readStream.pipe(response);
于 2012-09-16T02:36:32.783 回答
5

一个重要的原因是您可以在数据全部进入内存之前开始处理数据。想想“流媒体视频”,您可以在其中开始观看仍在加载的剪辑。在许多用例中,流将允许您在加载整个内容之前开始处理文件中的数据。

另一个常见的用例是当您只想读取一个对象,直到您检测到数据中的某些条件。假设您需要检查一个大文件是否包含“兔子”一词。如果使用回调模式,则需要将整个文件读入内存,然后遍历文件并检查单词是否在里面。使用流,您可能会在文件的第 5 行检测到单词,然后您可以关闭流,而无需加载整个内容。

There are obviously many more complex use cases, and there are still plenty of times where a callback still makes more sense for simplicity (such as if you needed to count the total times "rabbit" appeared, in which case you have to load the entire file anyway).

于 2013-08-04T20:54:11.297 回答