Skip to content

Instantly share code, notes, and snippets.

@josephg
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save josephg/9194035 to your computer and use it in GitHub Desktop.
Save josephg/9194035 to your computer and use it in GitHub Desktop.
// This version calls the _write callback after the data is sent.
Duplex = require('stream').Duplex;
var BCSocket = function(...) {
Duplex.call(this, {objectMode: true});
this.buffer = [];
};
BCSession.prototype = Object.create(Duplex.prototype);
BCSession._write = function(chunk, encoding, callback) {
this.buffer.push(chunk);
this.once("buffer flushed", callback);
};
exports.middleware = function(req, res) {
// This is about 1000 lines more complex in practice, but you get the idea
// Read messages & write reply
this.push(req.body.messages);
whenBufferNotEmpty(function() { // keep the request until we have data to send
process.nextTick(function() {
res.end(socket.buffer);
});
});
this.emit("buffer flushed"); // call _write callback
};
//// malfunctioning user code
// In this version of events, only one message will ever be sent in any response.
// Eg, if you do this:
session.write("reply1");
session.write("reply2");
// -> only "reply1" will be sent on the next hanging GET, and "reply2" will be sent on the *next* get.
// This version calls the _write callback immediately
Duplex = require('stream').Duplex;
var BCSocket = function(...) {
Duplex.call(this, {objectMode: true});
this.buffer = [];
};
BCSession.prototype = Object.create(Duplex.prototype);
BCSession._write = function(chunk, encoding, callback) {
this.buffer.push(chunk);
callback();
};
exports.middleware = function(req, res) {
// This is about 1000 lines more complex in practice, but you get the idea
// Read messages & write reply
this.push(req.body.messages);
whenBufferNotEmpty(function() { // keep the request until we have data to send
res.end(socket.buffer);
});
};
//// malfunctioning user code
// If you do this, 'a' is never written.
session.end('a', function() {
process.exit();
});
// If you do this, only one reply will be sent now.
session.on("readable", function() {
data = session.read();
session.write("reply1");
session.write("reply2");
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment