[英]Stream buffer to client in Express
I have request handler to send file from MongoDB (GridFS) to client like below, but it use data
variable so content is in memory. 我有请求处理程序将文件从MongoDB(GridFS)发送到客户端,如下所示,但是它使用data
变量,因此内容在内存中。 I need to make this in streaming mode and send file in chunks to client. 我需要在流模式下进行此操作,然后将文件分块发送给客户端。 I can't regognize how to pipe
buffer to response. 我无法识别如何通过pipe
缓冲区传递给响应。 Look at second code - it doesn't work, but show something what i need. 查看第二个代码-它不起作用,但显示一些我需要的东西。
Maybe it is useful: Data in GridFS is Base64 encoded, but may be changed if streaming can be more efficient. 也许很有用:GridFS中的数据是Base64编码的,但是如果流式传输可以更有效,则可以更改。
In-Memory version 内存版本
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'));
});
});
});
});
Streaming mode version 流模式版本
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();
});
});
});
});
Update 更新资料
I think I'm close to resolve this. 我想我已经解决了。 I found this works, but does't decode from Base64: 我发现这可行,但无法从Base64解码:
new GridStore(db, fileId, "r").open(function(err, gridStore) {
res.set('Content-Type', gridStore.contentType);
gridStore.stream(true).pipe(res);
});
I found a solution, but think that can be better. 我找到了解决方案,但认为可以更好。 I use base64-stream module to decode Base64 stream. 我使用base64-stream模块解码Base64流。 Solution below: 解决方案如下:
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'));
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.