在Express中将缓冲区传输到客户端

mar*_*osh 6 node.js express

我有请求处理程序将文件从MongoDB(GridFS)发送到客户端,如下所示,但它使用data变量,因此内容在内存中.我需要在流模式下进行此操作并将文件以块的形式发送给客户端.我无法确定如何pipe缓冲响应.看看第二个代码 - 它不起作用,但展示我需要的东西.

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

内存版本

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'));                   
        });
    });
  });
});
Run Code Online (Sandbox Code Playgroud)

流模式版本

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();
        });
    });
  });
});
Run Code Online (Sandbox Code Playgroud)

更新

我想我已接近解决这个问题了.我发现这有效,但不能从Base64解码:

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

jgi*_*ich 0

stream.on("data", function(chunk) {
    res.send(chunk.toString('utf8'));
});
Run Code Online (Sandbox Code Playgroud)