Skip to content

Commit 7fe8672

Browse files
committed
stream: fix Writable subclass instanceof checks
2a4b068 introduced a regression in where checking `instanceof` would fail for `Writable` subclasses inside the subclass constructor, i.e. before `Writable()` was called. Also, calling `null instanceof Writable` or `undefined instanceof Writable` would fail due to accessing the `_writableState` property of the target object. This fixes these problems. Ref: nodejs#8834 (comment)
1 parent 804d57d commit 7fe8672

2 files changed

Lines changed: 20 additions & 1 deletion

File tree

lib/_stream_writable.js

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -141,9 +141,12 @@ if (typeof Symbol === 'function' && Symbol.hasInstance) {
141141
realHasInstance = Function.prototype[Symbol.hasInstance];
142142
Object.defineProperty(Writable, Symbol.hasInstance, {
143143
value: function(object) {
144+
if (realHasInstance.call(this, object))
145+
return true;
146+
144147
// Trying to move the `realHasInstance` from the Writable constructor
145148
// to here will break the Node.js LazyTransform implementation.
146-
return object._writableState instanceof WritableState;
149+
return object && object._writableState instanceof WritableState;
147150
}
148151
});
149152
} else {

test/parallel/test-stream-inheritance.js

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,3 +27,19 @@ assert.ok(!(readable instanceof Transform));
2727
assert.ok(!(writable instanceof Transform));
2828
assert.ok(!(duplex instanceof Transform));
2929
assert.ok(transform instanceof Transform);
30+
31+
assert.ok(!(null instanceof Writable));
32+
assert.ok(!(undefined instanceof Writable));
33+
34+
// Simple inheritance check for `Writable` works fine in a subclass constructor.
35+
function CustomWritable() {
36+
assert.ok(this instanceof Writable, 'inhertis from Writable');
37+
assert.ok(this instanceof CustomWritable, 'inherits from CustomWritable');
38+
}
39+
40+
Object.setPrototypeOf(CustomWritable, Writable);
41+
Object.setPrototypeOf(CustomWritable.prototype, Writable.prototype);
42+
43+
new CustomWritable();
44+
45+
assert.throws(CustomWritable, /AssertionError: inhertis from Writable/);

0 commit comments

Comments
 (0)