Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node require returns undefined

I have an ErrorHandler class in my node code that handles all occuring errors.

Every Error has its own class. All classes are placed in seperate files so the folder structure is:

  • ErrorHandler.js
    • Error110.js
    • Error131.js
    • ...

ErrorHandler requires each of these files (along with some others)

var serverErrorCodes        = require('../../config/ErrorCodesConfig').server,
clientErrorCodes            = require('../../config/ErrorCodesConfig').client,
Error110                    = require('./errors/Error110').Error110,
Error131                    = require('./errors/Error131').Error131,
Error132                    = require('./errors/Error132').Error132,
Error133                    = require('./errors/Error133').Error133,
Error150                    = require('./errors/Error150').Error150;

When checking in node-debugger during runtime, the require result ist:

Closure:
  Error110: function Error110(params)
  Error131: function Error131(params)
  Error132: undefined
  Error133: undefined
  Error150: function Error150(messageObject, callback)

Error132 and Error133 are not available after the require, while the others are perfectly.

I've read that this happens if you have a require cycle and thus a required module (A) is requiring a module (B) which again requires module A. Node then ends this cycle by returning undefined after the first require. This is not the case.

So my last guess is that, at the time of execution, due to the asynchronous nature of node, the files are "not yet" required and thus only "some" files get included. But require is a synchronous function. I am not certain if this scenario is possible and how I would check for it.

I am clueless here, help is much appreciated.

Best regards, Worp

Edit 1:
As Travis Webb pointed out: This is wrong!
It also happens if your require a module that is already included somewhere earlier in the code. I thought about this but I am not requiring a module. And over all this doesn't seem to be true, since, for example, the util module needs to be included in every file that it is used, instead of just once.

like image 899
Worp Avatar asked Jul 31 '14 16:07

Worp


1 Answers

A simpler explanation is that module.exports is resolving to undefined inside the module that you are requiring. Post the code of the failing modules.

It also happens if your require a module that is already included somewhere earlier in the code.

This statement is incorrect.

due to the asynchronous nature of node, the files are "not yet" required

require is synchronous.

It is correct that if module A requires B, which in turn requires A, then A will be undefined in module B. But I'm not sure this is the problem.

like image 80
Travis Webb Avatar answered Oct 13 '22 10:10

Travis Webb