Skip to content

Commit 6c72783

Browse files
committed
stream: refactor writable _write
PR-URL: #50198
1 parent f09a50c commit 6c72783

File tree

2 files changed

+18
-12
lines changed

2 files changed

+18
-12
lines changed

lib/internal/streams/writable.js

+17-11
Original file line numberDiff line numberDiff line change
@@ -443,21 +443,21 @@ 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 = (state[kState] & kDefaultUTF8Encoding) !== 0 ? 'utf8' : state.defaultEncoding;
449-
} else {
450-
if (!encoding)
451-
encoding = (state[kState] & kDefaultUTF8Encoding) !== 0 ? 'utf8' : state.defaultEncoding;
452-
else if (encoding !== 'buffer' && !Buffer.isEncoding(encoding))
453-
throw new ERR_UNKNOWN_ENCODING(encoding);
454-
if (typeof cb !== 'function')
455-
cb = nop;
446+
if (cb == null || typeof cb !== 'function') {
447+
cb = nop;
456448
}
457449

458450
if (chunk === null) {
459451
throw new ERR_STREAM_NULL_VALUES();
460-
} else if ((state[kState] & kObjectMode) === 0) {
452+
}
453+
454+
if ((state[kState] & kObjectMode) === 0) {
455+
if (!encoding) {
456+
encoding = (state[kState] & kDefaultUTF8Encoding) !== 0 ? 'utf8' : state.defaultEncoding;
457+
} else if (encoding !== 'buffer' && !Buffer.isEncoding(encoding)) {
458+
throw new ERR_UNKNOWN_ENCODING(encoding);
459+
}
460+
461461
if (typeof chunk === 'string') {
462462
if ((state[kState] & kDecodeStrings) !== 0) {
463463
chunk = Buffer.from(chunk, encoding);
@@ -486,11 +486,17 @@ function _write(stream, chunk, encoding, cb) {
486486
errorOrDestroy(stream, err, true);
487487
return err;
488488
}
489+
489490
state.pendingcb++;
490491
return writeOrBuffer(stream, state, chunk, encoding, cb);
491492
}
492493

493494
Writable.prototype.write = function(chunk, encoding, cb) {
495+
if (encoding != null && typeof encoding === 'function') {
496+
cb = encoding;
497+
encoding = null;
498+
}
499+
494500
return _write(this, chunk, encoding, cb) === true;
495501
};
496502

test/parallel/test-stream-uint8array.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ const GHI = new Uint8Array([0x47, 0x48, 0x49]);
3838
assert(!(chunk instanceof Buffer));
3939
assert(chunk instanceof Uint8Array);
4040
assert.strictEqual(chunk, ABC);
41-
assert.strictEqual(encoding, 'utf8');
41+
assert.strictEqual(encoding, undefined);
4242
cb();
4343
})
4444
});

0 commit comments

Comments
 (0)