2014-04-25 99 views
6

我有請求處理程序將文件從MongoDB(GridFS)發送到像下面這樣的客戶端,但它使用data變量,所以內容在內存中。我需要在流模式下進行此操作,並將文件以塊的形式發送到客戶端。我無法確認如何緩衝響應。看第二個代碼 - 它不起作用,但顯示我需要的東西。流緩存到客戶端在快遞

也許它很有用: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'));     
     }); 
    }); 
    }); 
}); 

流模式版本

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); 
}); 
+0

marioosh做你看我的答案嗎? – malix

回答

0
stream.on("data", function(chunk) { 
    res.send(chunk.toString('utf8')); 
}); 
1

我發現了一個解決方案,但認爲可以更好。我使用base64-stream模塊來解碼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); 
      gridStore.stream(true).pipe(base64.decode()).pipe(res); 
     }); 
    }); 
}); 
1
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); 
}