Skip to content

Commit

Permalink
stream: make Writable#end() accept a callback function
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
TooTallNate committed Feb 5, 2013
1 parent cd42f56 commit a9c4a20
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 2 deletions.
17 changes: 15 additions & 2 deletions lib/_stream_writable.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 changes: 29 additions & 0 deletions test/simple/test-stream2-writable.js
Original file line number Diff line number Diff line change
Expand Up @@ -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();
});
});

0 comments on commit a9c4a20

Please sign in to comment.