Last Updated: February 25, 2016
·
5.086K
· michalkow

Streaming files to MongoDB using Socket.io and GridFS

Today I discovered how easy it is to send a file over the web sockets directly to MongoDB GridFS.
It is possible thanks to two amazing node modules. One of them is Naoyuki Kanezawa's Socket.IO stream. The other one is Aaron Heckmann's gridfs-stream.

I will get right to the point. I will just assume you read the documentation of both modules, and included them into your Node.js project. The client side code will be no different then the example in Socket.IO stream project documentation. This is example how receiving of the file and writing it to GridFS could look like:

io.sockets.on('connection', function (socket) {
    ss(socket).on('uploadFile', function (stream, data, callback) {
        var writestream = gfs.createWriteStream();
        stream.pipe(writestream);
    });  
    ...
});

It is not too complicated, because those two modules work perfectly together. If you use MongoDB and Socket.io in your project, I would recommend to try out this method of uploading and storing data.

Have a fresh tip? Share with Coderwall community!

Post
Post a tip