Browse Source

stream: make Writable#end() accept a callback function

This is more backwards-compatible with stream1 streams like `fs.WriteStream`
which would allow a callback function to be passed in as the only argument.

Closes #4719.
v0.9.9-release
Nathan Rajlich 12 years ago
parent
commit
a9c4a20331
  1. 17
      lib/_stream_writable.js
  2. 29
      test/simple/test-stream2-writable.js

17
lib/_stream_writable.js

@ -289,20 +289,33 @@ Writable.prototype._write = function(chunk, cb) {
});
};
Writable.prototype.end = function(chunk, encoding) {
Writable.prototype.end = function(chunk, encoding, cb) {
var state = this._writableState;
// ignore unnecessary end() calls.
if (state.ending || state.ended || state.finished)
return;
if (typeof chunk === 'function') {
cb = chunk;
chunk = null;
encoding = null;
} else if (typeof encoding === 'function') {
cb = encoding;
encoding = null;
}
state.ending = true;
if (chunk)
this.write(chunk, encoding);
this.write(chunk, encoding, cb);
else if (state.length === 0 && !state.finishing && !state.finished) {
state.finishing = true;
this.emit('finish');
state.finished = true;
if (cb) process.nextTick(cb);
} else if (cb) {
this.once('finish', cb);
}
state.ended = true;
};

29
test/simple/test-stream2-writable.js

@ -251,3 +251,32 @@ test('write callbacks', function (t) {
});
tw.end();
});
test('end callback', function (t) {
var tw = new TestWriter();
tw.end(function () {
t.end();
});
});
test('end callback with chunk', function (t) {
var tw = new TestWriter();
tw.end(new Buffer('hello world'), function () {
t.end();
});
});
test('end callback with chunk and encoding', function (t) {
var tw = new TestWriter();
tw.end('hello world', 'ascii', function () {
t.end();
});
});
test('end callback after .write() call', function (t) {
var tw = new TestWriter();
tw.write(new Buffer('hello world'));
tw.end(function () {
t.end();
});
});

Loading…
Cancel
Save