使用NodeJS Stream的一个例子
Table of Contents
1 what is stream ?
2 为什么要使用stream呢?
{原文}why you should use streams
一个简单的http文件服务器
var http = require('http'); var fs = require('fs'); var server = http.createServer(function (req, res) { fs.readFile(__dirname + '/data.txt', function (err, data) { if (err) { res.statusCode = 500; res.end(String(err)); } else res.end(data); }); }); server.listen(8000);
改用stream的方式
var http = require('http'); var fs = require('fs'); var server = http.createServer(function (req, res) { var stream = fs.createReadStream(__dirname + '/data.txt'); stream.on('error', function (err) { res.statusCode = 500; res.end(String(err)); }); stream.pipe(res); }); server.listen(8000);
好处是什么呢?
- 代码更清晰
- 避免回调嵌套
- 每次读取到一个数据段chunk,就会立刻将数据发往客户端 ,所以,node不必将完整的文件数据载入内存
改进后的代码,若还嫌长的啰嗦,有一个库可供使用
var http = require('http'); var filed = require('filed'); var server = http.createServer(function (req, res) { filed(__dirname + '/data.txt').pipe(res); }); server.listen(8000);
filed 模块 提供mime types ,etag 缓存,错误处理支持
压缩响应内容,使用oppressor
var http = require('http'); var filed = require('filed'); var oppressor = require('oppressor'); var server = http.createServer(function (req, res) { filed(__dirname + '/data.txt') .pipe(oppressor(req)) .pipe(res) ; }); server.listen(8000);
Date: 2012-09-02 23:02:49 CST
HTML generated by org-mode 6.33x in emacs 23