Store images in Mongodb serve them with Nodejs

image, mongodb, node.js

Solution

I would strongly advise against serving images from MongoDB.

It would be better to store them on a static filestore (S3) and maybe keep the path in MongoDB.

You would probably use base64 encoding to put the file into mongodb: http://www.greywyvern.com/code/php/binary2base64/ (or just base64 shell utility).

If you're just using regular documents then the performance cost is relatively low (so long as caching is good). If you're using a mixed database where you have GridFS and regular documents you're going to need a lot of RAM on your server(s) -- the GridFS queries will run completely differently from the document queries.

Converting the image might work like this:

var base64Data = imagefile.replace(/^data:image\/png;base64,/,""),
var dataBuffer = new Buffer(base64Data, 'base64');

// below line won't actually work but it's something along the lines of what you want:

db.foo.insert({magic: 123, etc... img: dataBuffer.toString()})

Problem

I understand Mongodb can store images in two ways. - in a regular document by storing the image as binary - via Gridfs for managing larger images. For simplicity and because the images I plan to server are small, I will go for option 1. To serve the images to a browser I am using nodejs. My question is how difficult will this be? How do you turn binary data to an actual image a browser will understand? What type of encoding is involved? Could you point me to tutorials/examples elsewhere on the web? By the way I know this may not be good idea for performance reasons, I plan to cache the images once served. I just want to avoid the file-system all-together.

Original source