Skip to content

Instantly share code, notes, and snippets.

@zertosh
Created November 8, 2015 03:15
Show Gist options
  • Save zertosh/b68478fbfe54d7270961 to your computer and use it in GitHub Desktop.
Save zertosh/b68478fbfe54d7270961 to your computer and use it in GitHub Desktop.
duplexer2 example for node 4.x
#!/usr/bin/env node
"use strict";
const stream = require("readable-stream");
const duplexer2 = require("duplexer2");
const writable = new class extends stream.Writable {
constructor() {
super({objectMode: true})
}
_write(input, encoding, done) {
if (readable.push(input)) {
return done();
} else {
readable.once("drain", done);
}
}
};
const readable = new class extends stream.Readable {
constructor() {
super({objectMode: true})
}
_read() {
// no-op
}
};
// simulate the readable thing closing after a bit
writable.once("finish", () => {
setTimeout(() => {
readable.push(null);
}, 500);
});
var duplex = duplexer2(writable, readable);
duplex.on("data", e => {
console.log("got data", JSON.stringify(e));
});
duplex.on("finish", () => {
console.log("got finish event");
});
duplex.on("end", () => {
console.log("got end event");
});
duplex.write("oh, hi there", () => {
console.log("finished writing");
});
duplex.end(() => {
console.log("finished ending");
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment