Read chunk from Gridfs and convert to Buffer

江枫思渺然 提交于 2019-12-14 02:20:24

问题


I got a question about buffer. Here is my code:

var Grid = require('gridfs-stream');
var mongodb = require('mongodb');
var gfs = Grid(db, mongodb);
var deferred = Q.defer();
var image_buf = new Buffer('buffer');
var readableStream = gfs.createReadStream(name);

readableStream.on('data',function(chunk){  
    console.log(chunk);
    image_buf = Buffer.concat([image_buf, chunk]);
    console.log(image_buf)//differ from the chunk above
});
readableStream.on('end',function(){
    db.close();
    deferred.resolve(image_buf);
})
return deferred.promise;

What I'm doing is to read an image from MongoDB and put it in the gridfs-stream. I really want to retrieve all chunks in the stream and pass them to another variable so that I can reuse these chunks to draw an image in another API. Therefore I use image_buf and Buffer to perform the task. However, I get a completely different buffer string. As you can see in the above code, I consoled the chunk and the image_buf I got, but they are totally different. Can anyone tell me the reason for this and how can I correctly collect all chunks? Thanks a lot!!!

UPDATE: OK, so I figured it out now: I will append my code below for anyone who is struggling with the same problem as mine:

    readableStream.on('data',function(chunk){ 
        console.log("writing!!!");
        if (!image_buf)
            image_buf = chunk;
        else image_buf = Buffer.concat([image_buf, chunk]);
    });

回答1:


The update provided by question poster does not work . So i am going to provide answer of my own. Instead of using new Buffer('buffer') it is better to use an simple array and push chunks into it and use Buffer.concat(bufferArray) at the end to get buffer of stream like this:

var readableStream = gfs.createReadStream(name);
var bufferArray = [];
readableStream.on('data',function(chunk){  
    bufferArray.push(chunk);
});
readableStream.on('end',function(){
    var buffer = Buffer.concat(bufferArray);
    deferred.resolve(buffer);
})


来源:https://stackoverflow.com/questions/38763080/read-chunk-from-gridfs-and-convert-to-buffer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!