Check if object is instance of EventEmitter

2019-09-01 11:13发布

问题:

I am a looking for a way, other than duck typing, to discover if an object inherits from EventEmitter

https://nodejs.org/api/events.html

I suppose I could just check if the object has a couple of those functions that event emitters have been this is just dirty.

Is there a better way to do this with Node.js? Also, if there is a way to determine if something is a stream on top of being an event emitter, that would be useful too.

回答1:

To check if an object is an instance of an EventEmmitter you can compare it with the EventEmitter from within node. Just require the "events" module which will expose an EventEmmitter.

I found and modified a little snippet for you:

var http = require("http");

http.get("http://nodejs.org/", function (res) {
    // res is an EventEmitter that represents the HTTP response
    console.log(res instanceof require("events").EventEmitter); // true
    console.log(typeof res); // object
});