node.js instanceof and cleartextStream

node.js instanceof and cleartextStream

本文关键字:cleartextStream and instanceof js node      更新时间:2023-09-26

我正在尝试验证我的原型的两个参数是否是我期望的实例。我需要知道cleartextStream是否是node.js文档称为tls.cleartextStream的实例,以及管理器是否是我在另一个文件中自己定义的原型的实例。

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 (...)

直到现在都"好"。当执行该位时,我得到:

if (!(cleartextStream instanceof tls.cleartextStream) || !(manager instanceof
TypeError: Expecting a function in instanceof check, but got #<CleartextStream>

并且,对于经理部分:

if (!(cleartextStream instanceof tls) || !(manager instanceof clientManager))
TypeError: Expecting a function in instanceof check, but got [object Object]

那么,我将如何检查这些实例呢?

编辑:阅读这篇文章后,我发现对象实际上是构造函数的实例,因此将我的代码修改为

if (!(cleartextStream instanceof tls) || !(manager instanceof clientManager.constructor))

实际上修复了第二个问题。尽管如此,第一个仍然存在。

TLS 不会导出这些类供您检查,所以我没有看到真正干净的方法。

您可以做的一件事是检查对象的原型是否是您所期望的。

target_proto = new tls.createSecurePair().cleartext.__proto__
if (target_proto !== clearTextStream.proto)
  throw(....)

需要注意的一件事是,只有当您和该对象的创建者引用相同版本的模块(例如,使用相同的路径导入等)时,这才有效,以便原型对象将相等地进行比较。