Created
April 16, 2012 23:04
-
-
Save patcoll/2402227 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
nice. probably don't need the extra
Buffer
wrap code:this.emit('data', doc[this.field])