Skip to content

Instantly share code, notes, and snippets.

@patcoll
Created April 16, 2012 23:04
Show Gist options
  • Save patcoll/2402227 to your computer and use it in GitHub Desktop.
Save patcoll/2402227 to your computer and use it in GitHub Desktop.
// I wanted a proof-of-concept for streaming binary data from a MongoDB document with Mongoose.
// I'm using express as web framework here but you should be able to pipe to anything that expects a stream.
// Based on https://gist.github.com/1403797
//// [ other express app stuff... ]
app.get('/files/:file', function(req, res, next) {
var queryfileId = req.params.file;
var GrabBinaryForField = require('./streamformatters').GrabBinaryForField;
// "buffer" is the field on my model that stores the binary data
return Asset.findById(queryfileId).select('buffer').stream().pipe(new GrabBinaryForField('buffer')).pipe(res);
});
var Stream = require('stream').Stream;
function GrabBinaryForField(field) {
this.field = field;
Stream.call(this);
this.writable = true;
this._done = false;
}
GrabBinaryForField.prototype.__proto__ = Stream.prototype;
GrabBinaryForField.prototype.write = function (doc) {
this.emit('data', new Buffer(doc[this.field]));
return true;
}
GrabBinaryForField.prototype.end =
GrabBinaryForField.prototype.destroy = function () {
if (this._done) return;
this._done = true;
// done
this.emit('end');
}
exports.GrabBinaryForField =
module.exports.GrabBinaryForField = GrabBinaryForField;
@aheckmann
Copy link

nice. probably don't need the extra Buffer wrap code: this.emit('data', doc[this.field])

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment