您的位置:首页 > Web前端 > Node.js

Node:初识Stream

2016-03-03 21:24 711 查看
初步认识nodejs中的stream模块。

Stream是什么?为什么需要用Steam?

先看下面两幅图,寻找差异。

图一:(图片被压缩了,请按ctrl+滚轮 放大屏幕看一下)



图二:



两个程序分别请求了同一个文件,输出到页面,非常简单的操作。

注意,区别之一就是 waiting(TTFB)。

要认识到差异,首先得看看TTFB是什么。

Load time is how long it takes for a webpage to be loaded and usable by a browser. Often time in web page delivery a page is compressed in the Gzip format to make the size of the download smaller. This practices prevents the first byte from being sent until the compression is complete and increases the TTFB significantly.

具体请看这里

简单来说 TTFB就是加载首个字节需要的时间。

图一中TTFB只需要2.06ms,而图二花了354.98ms。

这里可以看出,以stream的方式从磁盘中读书文件,效率还是挺高的。

图一的代码:

var http = require( 'http' ),
fs = require( 'fs' );

var server = http.createServer( function ( req, res) {
var stream = fs.createReadStream('facebook.json' );
stream.pipe( res );

})

server.listen( 8000 );
console.log("server start")


图二的代码:

var http = require( 'http' ),
fs = require( 'fs' );

var server = http.createServer( function ( req, res) {
fs.readFile('facebook.json', function ( err, data) {
res.end( data );

})
})

server.listen( 3000 );
console.log("server start")


这里唯一不同的是,图一以stream的方式读取文件。

为什么需要Stream?

按照图二的方式进行I/O请求时,程序必须等文件全部读取成功时,才会返回相应的数据,这样一来,页面可能会造成阻塞,TTFB也比较大,特别是并发量比较大的情况下,是比较糟糕的体验。

按照图一,以stream的方式读取文件时,不必等所有的文件的数据读取完,只有响应了请求,从磁盘中读取到数据时,它会立即返回,所以它的TTFB较小,体验相应也会好些。

未完待续

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  nodejs fs stream