从Gridfs中读取块并转换为Buffer [英] Read chunk from Gridfs and convert to Buffer

查看:77
本文介绍了从Gridfs中读取块并转换为Buffer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于缓冲区的问题.这是我的代码:

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;

我正在做的是从MongoDB中读取图像并将其放入gridfs流中.我真的很想检索流中的所有块并将它们传递给另一个变量,以便我可以重用这些块在另一个API中绘制图像.因此,我使用image_buf和Buffer执行任务.但是,我得到了一个完全不同的缓冲区字符串.如您在上面的代码中看到的,我对获得的块和image_buf进行了控制台,但是它们完全不同.谁能告诉我这样做的原因,以及如何正确收集所有块?非常感谢!!!

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

推荐答案

问题发布者提供的更新无效.因此,我将提供自己的答案.与其使用new Buffer('buffer'),不如使用一个简单的数组并将块推入其中,并在末尾使用Buffer.concat(bufferArray)来获取流的缓冲区,如下所示:

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

这篇关于从Gridfs中读取块并转换为Buffer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆