I'm trying to verify whether two arguments to my prototype are instances of what I'm expecting them to be. I need to know whether cleartextStream is an instance of what node.js docs call tls.cleartextStream and whether manager is an instance of a prototype I've defined myself in another file.
var tls = require('tls'),
clientManager = require('./client_manager');
var Client = function (cleartextStream, manager) {
/*
* Both arguments must be proper instances of the expected classes.
*/
if (!(cleartextStream instanceof tls.cleartextStream) || !(manager instanceof clientManager))
throw (...)
All "good" until now. When that bit is executed, I get:
if (!(cleartextStream instanceof tls.cleartextStream) || !(manager instanceof
TypeError: Expecting a function in instanceof check, but got #<CleartextStream>
and, for the manager part:
if (!(cleartextStream instanceof tls) || !(manager instanceof clientManager))
TypeError: Expecting a function in instanceof check, but got [object Object]
So, how would I go about checking for these instances?
EDIT: After reading this post, I've found that objects are actually instances of a constructor, thus modifying my code to
if (!(cleartextStream instanceof tls) || !(manager instanceof clientManager.constructor))
Actually fixes the second issue. Still, the first one persists.
tls doesn't export those classes for you to check against, so I don't see a really clean way to do it.
One thing you could do is to check if the prototype of the object is what you expect it to be.
target_proto = new tls.createSecurePair().cleartext.__proto__
if (target_proto !== clearTextStream.proto)
throw(....)
One thing to watch out for is that this will only work if you and the creator of this object were referring to the same version of the module (e.g. imported with the same paths, etc.), so that the proto objects will compare as equal.