Skip to content

Writable's instanceof implementation is faulty #14943

Description

@Li357
  • Version: Node v8.4.0
  • Platform: macOS
  • Subsystem: Stream

The implementation for Writable's @@hasInstance method is faulty. As described in this Stack Overflow post:

In this snippet, the statement f instanceof PipeWritable returns true (Node v8.4.0):

const stream = require('stream');
const fs = require('fs');

class PipeWritable extends stream.Writable {
    constructor () {
        super();
    }
}

const s = new PipeWritable();
const f = fs.createWriteStream('/tmp/test');

console.log(f instanceof PipeWritable); // true ... ???

Because of the hasInstance implementation, this line:

return object && object._writableState instanceof WritableState;

Allows for Writables to be subclasses of Writable. This is a side-effect of Duplex parasitically inheriting from Writable, making new Duplex() instanceof Writeable true but also making Writables instances of Writable subclasses. Maybe add another check to make sure only Duplexes can be instances of Writables, but not Writables instances of Writable subclasses?

[refack: replaced code copy with code reference]

Activity

  1. added
    streamIssues and PRs related to Node.js streams.
    on Aug 19, 2017
  2. addaleax commented on Aug 19, 2017

    @addaleax
    Member

    Can you try this diff?

    diff --git a/lib/_stream_writable.js b/lib/_stream_writable.js
    index 6e0eaf45b546..7de77958d56b 100644
    --- a/lib/_stream_writable.js
    +++ b/lib/_stream_writable.js
    @@ -179,6 +179,8 @@ if (typeof Symbol === 'function' && Symbol.hasInstance) {
         value: function(object) {
           if (realHasInstance.call(this, object))
             return true;
    +      if (this !== Writable)
    +        return false;
     
           return object && object._writableState instanceof WritableState;
         }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    streamIssues and PRs related to Node.js streams.

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions