Nodejs + Require instanceof behaviour

后端 未结 2 544
小蘑菇
小蘑菇 2021-01-04 08:15

I\'m encountering a strange behaviour with instanceof in NodeJs. I\'m trying to creating a module which throws exceptions which can be caught by consuming modules and dealt

相关标签:
2条回答
  • 2021-01-04 08:56

    Cannot reproduce the problem. Working for me using version 0.12 and 4.0.0 (tested both).

    What you should consider in future is that you reference your OWN modules using relative paths (absolute ones are not system independent). If you don't, you normally reference core modules of Node.js directly or NPM installed ones. So change 'mymodule' to './mymodule' (change path accordingly).

    0 讨论(0)
  • 2021-01-04 09:02

    FOUND IT

    To use your example, in file one.js I had:

    var mod = require('mymodule');
    

    but in another file two.js I had:

    var mod = require('Mymodule');
    

    and everything seemed to work exactly the same, except when you compared an error created from one.js using instanceof in two.js!.

    Absurdly, node.js allows you to do a case-insensitive require, except it's not really case-insensitive, it actually requires your file twice, which is why instanceof returns false – the constructors are two different functions from two different module instances!

    TL;DR

    Make sure all your require strings are case-consistent.

    0 讨论(0)
提交回复
热议问题