在Express中将streamcaching到客户端

我有请求处理程序从MongoDB(GridFS)发送文件到下面的客户端,但它使用datavariables,所以内容在内存中。 我需要在stream模式下将其发送到客户端。 我无法确认如何缓冲响应。 看第二个代码 – 它不工作,但显示我需要的东西。

也许这很有用:GridFS中的数据是Base64编码的,但是如果stream式传输效率更高,则可能会改变。

内存版本

 router.get('/get/:id', function(req,res){ getById(req.params.id, function(err, fileId){ new GridStore(db, fileId, "r").open(function(err, gridStore) { res.set('Content-Type', gridStore.contentType); var stream = gridStore.stream(true); var data = ''; stream.on("data", function(chunk) { data += chunk; }); stream.on("end", function() { res.send(new Buffer(data, 'base64')); }); }); }); }); 

stream模式版本

 router.get('/get/:id', function(req,res){ getById(req.params.id, function(err, fileId){ new GridStore(db, fileId, "r").open(function(err, gridStore) { res.set('Content-Type', gridStore.contentType); var stream = gridStore.stream(true); stream.on("data", function(chunk) { new Buffer(chunk, 'base64').pipe(res); }); stream.on("end", function() { res.end(); }); }); }); }); 

更新

我想我已经接近解决这个问题了。 我发现这个工程,但不解码从Base64:

 new GridStore(db, fileId, "r").open(function(err, gridStore) { res.set('Content-Type', gridStore.contentType); gridStore.stream(true).pipe(res); }); 

我find了一个解决scheme,但认为可以做得更好。 我使用base64stream模块来解码Base64stream。 解决scheme如下

 router.get('/get/:id', function(req,res){ getById(req.params.id, function(err, fileId){ new GridStore(db, fileId, "r").open(function(err, gridStore) { res.set('Content-Type', gridStore.contentType); gridStore.stream(true).pipe(base64.decode()).pipe(res); }); }); }); 
 exports.sendFile = function(db, res, fileId) { var grid = require('gridfs-stream'); var gfs = grid(db, mongoose.mongo); var on_error = function(){ res.status(404).end(); }; var readstream = gfs.createReadStream({ filename: fileId, root: 'r' }); readstream.on('error', function(err) { if (('\'' + err + '\'') === '\'Error: does not exist\'') { return on_error && on_error(err); } throw err; }); return readstream.pipe(res); } 
 stream.on("data", function(chunk) { res.send(chunk.toString('utf8')); });