Skip to content

Instantly share code, notes, and snippets.

@psi-4ward
Created August 31, 2013 16:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save psi-4ward/6399206 to your computer and use it in GitHub Desktop.
Save psi-4ward/6399206 to your computer and use it in GitHub Desktop.
FormidableGridFS Handler
var IncomingForm = require('formidable');
var util = require('util');
var EventEmitter = require('events').EventEmitter;
var GridStore = require('mongodb').GridStore;
var pauseStream = require('pause-stream');
var ObjectID = require('mongodb').ObjectID;
function IncomingFormGridFS(opts) {
if(!(this instanceof IncomingFormGridFS)) return new IncomingFormGridFS(opts);
if(!opts.mongodbConnection) throw "Please provide mongodbConnection option!";
EventEmitter.call(this);
this.mongodbConnection = opts.mongodbConnection;
this.error = null;
this.ended = false;
this.maxFields = opts.maxFields || 1000;
this.maxFieldsSize = opts.maxFieldsSize || 2 * 1024 * 1024;
this.keepExtensions = opts.keepExtensions || false;
this.uploadDir = opts.uploadDir;
this.encoding = opts.encoding || 'utf-8';
this.headers = null;
this.type = null;
this.hash = false;
this.bytesReceived = null;
this.bytesExpected = null;
this._parser = null;
this._flushing = 0;
this._fieldsSize = 0;
this.openedFiles = [];
return this;
}
util.inherits(IncomingFormGridFS, IncomingForm);
IncomingFormGridFS.prototype.handlePart = function(part) {
var self=this;
if(!part.filename) return self.handlePart(part);
var pStream = pauseStream();
part.pipe(pStream.pause());
var fileMeta = {
name: part.filename,
path: 'void', // TODO
type: part.mime
};
self.openedFiles.push(fileMeta);
self.emit('fileBegin', part.name, fileMeta);
new GridStore(self.mongodbConnection, new ObjectID(), fileMeta.name , 'w', {
metadata: {
filename: fileMeta.name
},
content_type: part.mime
}).open(function(err, gridFile) {
self._flushing++;
pStream.on('data', function(buffer) {
pStream.pause();
gridFile.write(buffer, function(err) {
if(err) console.error(err);
pStream.resume();
});
});
pStream.on('end', function() {
gridFile.close(function(err, fileData) {
fileMeta.hash = fileData.md5;
fileMeta.length = fileData.length;
fileMeta._id = fileData._id;
fileMeta.uploadDate = fileData.uploadDate;
self._flushing--;
self.emit('file', part.name, fileMeta);
self._maybeEnd();
});
});
pStream.resume();
});
};
IncomingFormGridFS.prototype._error = function(err) {
if(this.error || this.ended) {
return;
}
console.log('gridfs incfrm _ERROR ');
this.error = err;
this.pause();
this.emit('error', err);
// no need to delete files, GridFS kicks it when we dont close the stream probably
};
module.exports = IncomingFormGridFS;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment