Serving out saved Buffer from Mongo

Problem

I'm trying to serve out images that I have stored in a Mongo document. I'm using express, express-resource and mongoose.

The data, which is a JPG, is stored in a Buffer field in my schema. Seems like it's getting there correctly as I can read the data using the cli.

Then I run a find, grab the field and attempt sending it. See code:

res.contentType('jpg');
res.send(img);

I don't think it's a storage issue because I'm performing the same action here:

var img = fs.readFileSync(
    __dirname + '/../../img/small.jpg'
);
res.contentType('jpg');
res.send(img);

In the browser the image appears (as a broken icon).

I'm wondering if it's an issue with express-resource because I have the format set to json, however I am indeed overriding the content type before sending the data.

scratches head

Problem courtesy of: ddibiase

Solution

I managed to solve this myself. Seems like I was using the right method to send the data from express, but wasn't storing it properly (tricky!).

For future reference to anyone handling image downloads and managing them in Buffers, here is some sample code using the request package:

request(
    {
        uri: uri,
        encoding: 'binary'
    },
    function (err, response, body)
    {
        if (! err && response.statusCode == 200)
        {
            var imgData = new Buffer(
                body.toString(),
                'binary'
            ).toString('base64');
            callback(null, new Buffer(imgData, 'base64'));
        }

    }
);

Within Mongo you need to setup a document property with type Buffer to successfully store it. Seems like this issue was due to how I was saving it into Mongo.

Hopefully that saves someone time in the future. =)

Solution courtesy of: ddibiase

Discussion

There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.