Read chunk from Gridfs and convert to Buffer

2019-07-09 11:25发布

问题:

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