Last active
August 29, 2015 14:16
-
-
Save emilbayes/0934422cae968bf9b8ef to your computer and use it in GitHub Desktop.
Stream Example
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'); | |
var messageStream = require('./message-stream'); | |
var jsonify = new stream.Transform({ | |
writableObjectMode: true, | |
transform: function(chunk, enc, cb) { | |
this.push(JSON.stringify(chunk, null, 2) + '\n'); | |
cb(); | |
} | |
}); | |
messageStream({interval: 50}).pipe(jsonify).pipe(process.stdout); |
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'); | |
var util = require('util'); | |
var objectAssign = require('object-assign') | |
util.inherits(MessageStream, stream.Readable); | |
function MessageStream(options) { | |
if (!(this instanceof MessageStream)) return new MessageStream(options); | |
this.options = objectAssign({ | |
interval: 2000, | |
string: 'Hello World' | |
}, options, { | |
objectMode: true, | |
highWaterMark: 0 | |
}); | |
stream.Readable.call(this, this.options); | |
} | |
MessageStream.prototype._read = function() { | |
var self = this; | |
setTimeout(function() { | |
self.push({message: self.options.string}); | |
}, this.options.interval); | |
} | |
module.exports = MessageStream; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment