Skip to content

Commit e9cf37a

Browse files
committed
stream: refactor writable _write
PR-URL: nodejs#50198
1 parent 8f742bb commit e9cf37a

1 file changed

Lines changed: 17 additions & 4 deletions

File tree

lib/internal/streams/writable.js

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -443,9 +443,8 @@ Writable.prototype.pipe = function() {
443443
function _write(stream, chunk, encoding, cb) {
444444
const state = stream._writableState;
445445

446-
if (typeof encoding === 'function') {
447-
cb = encoding;
448-
encoding = null;
446+
if (cb == null || typeof cb !== 'function') {
447+
cb = nop;
449448
}
450449

451450
if (!encoding)
@@ -458,7 +457,15 @@ function _write(stream, chunk, encoding, cb) {
458457

459458
if (chunk === null) {
460459
throw new ERR_STREAM_NULL_VALUES();
461-
} else if ((state[kState] & kObjectMode) === 0) {
460+
}
461+
462+
if ((state[kState] & kObjectMode) === 0) {
463+
if (!encoding) {
464+
encoding = (state[kState] & kDefaultUTF8Encoding) !== 0 ? 'utf8' : state.defaultEncoding;
465+
} else if (encoding !== 'buffer' && !Buffer.isEncoding(encoding)) {
466+
throw new ERR_UNKNOWN_ENCODING(encoding);
467+
}
468+
462469
if (typeof chunk === 'string') {
463470
if ((state[kState] & kDecodeStrings) !== 0) {
464471
chunk = Buffer.from(chunk, encoding);
@@ -487,11 +494,17 @@ function _write(stream, chunk, encoding, cb) {
487494
errorOrDestroy(stream, err, true);
488495
return err;
489496
}
497+
490498
state.pendingcb++;
491499
return writeOrBuffer(stream, state, chunk, encoding, cb);
492500
}
493501

494502
Writable.prototype.write = function(chunk, encoding, cb) {
503+
if (encoding != null && typeof encoding === 'function') {
504+
cb = encoding;
505+
encoding = null;
506+
}
507+
495508
return _write(this, chunk, encoding, cb) === true;
496509
};
497510

0 commit comments

Comments
 (0)