Nodejs + Require instanceof behaviour

独自空忆成欢 提交于 2019-11-30 17:47:57

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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!