Node.js 流数据
下面的程序演示如何用数据流的方式来梳理文件resource.json:
var fs = require('fs'); var stream = fs.createReadStream('./resource.json'); stream.on('data', function (chunk) { console.log(chunk); }); stream.on('end', function () { console.log('finished'); });
下面的程序演示如何在HTTP服务器上读取一张图片的数据流并显示在客户端:
var http = require('http'); var fs = require('fs'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'image/png'}); fs.createReadStream('./image.png').pipe(res); }).listen(3000); console.log('Server running at http://localhost:3000/');