Skip to content

Instantly share code, notes, and snippets.

@isaacs
Created August 12, 2013 21:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save isaacs/6215412 to your computer and use it in GitHub Desktop.
Save isaacs/6215412 to your computer and use it in GitHub Desktop.
var Writable = require('stream').Writable;
var util = require('util');
var assert = require('assert');
function W(o) {
Writable.call(this, o);
setTimeout(function() {
this.ready = true
this.emit('ready');
}.bind(this), 1000);
this.flushed = false;
this.on('finish', function() {
console.log('finish', this.flushed);
assert(this.flushed);
});
this._writableState.decodeStrings = false;
this.on('prefinish', function() {
console.log('prefinish', this.flushed);
});
}
util.inherits(W, Writable);
W.prototype._write = function(chunk, encoding, cb) {
assert(!this.flushed);
if (!this.ready) {
this.once('ready', function() {
this._write(chunk, encoding, cb);
});
} else {
var state = this._writableState;
console.error('write', chunk);
if (state.ending && state.buffer.length === 1) {
console.error('last write, flush trailers with it');
this.flushed = true;
}
setTimeout(cb);
}
};
W.prototype.end = function(chunk, encoding, cb) {
if (!this.ready) {
this.once('ready', function() {
this.end(chunk, encoding, cb);
});
} else {
if (chunk && typeof chunk !== 'function') {
if (typeof encoding === 'function') {
cb = encoding;
encoding = null;
}
var self = this;
this.write(chunk, encoding);
chunk = null;
encoding = null;
}
var state = this._writableState;
if (state.buffer.length === 0) {
console.error('no pending writes, flush trailers with it');
this.flushed = true;
}
Writable.prototype.end.call(this, chunk, encoding, cb);
}
};
f1();
function f1() {
var w = new W();
w.write('a');
setTimeout(function() {
w.end(function() {
console.error('end cb');
f2();
});
}, 200);
}
function f2() {
var w = new W();
w.write('a');
w.write('b');
w.write('c');
w.write('d');
w.write('e');
w.end(function() {
console.error('end cb');
f3();
});
}
function f3() {
var w = new W();
w.write('a');
w.end('b', function() {
console.error('end cb');
f4();
});
}
function f4() {
var w = new W();
w.end('a', function() {
console.error('end cb');
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment