Last active
December 16, 2015 14:29
-
-
Save ForbesLindesay/5448801 to your computer and use it in GitHub Desktop.
Duplexer.js for node v0.10
This file contains hidden or 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 vNext = !!require('stream').Duplex; | |
| var DuplexBase = require(vNext ? 'stream' : 'readable-stream').Duplex; | |
| var Readable = require(vNext ? 'stream' : 'readable-stream').Readable; | |
| function Duplex(writer, reader, options) { | |
| DuplexBase.call(this, options); | |
| var _reader = new Readable(); | |
| _reader.wrap(reader); | |
| reader = _reader; | |
| var self = this; | |
| this._read = function (size) { | |
| var buf; | |
| read(); | |
| function read() { | |
| while (buf = reader.read(size)) | |
| if (!self.push(buf)) return; | |
| reader.once('readable', read); | |
| } | |
| }; | |
| reader.on('end', function () { | |
| self.push(null); | |
| }); | |
| this._write = function (chunk, encoding, callback) { | |
| if (writer.write(chunk, encoding)) { | |
| callback(); | |
| } else { | |
| writer.once('drain', callback); | |
| } | |
| }; | |
| this.on('finish', function () { | |
| writer.end(); | |
| }); | |
| reader.on('error', function (err) { | |
| self.emit('error', err); | |
| }); | |
| writer.on('error', function (err) { | |
| self.emit('error', err); | |
| }); | |
| } | |
| Duplex.prototype = Object.create(DuplexBase.prototype); | |
| Duplex.prototype.constructor = Duplex; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment