Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJs Require module returns an empty object

Tags:

node.js

I'm using NodeJS 8 LTS.

I have 3 js scripts where:

// main.js
const dom = require ('./Domains/Domains');
const factory = require ('./Domains/Factory');
(async () => {
    const Domain = await factory.foo();  // <=== Error

})();

// Domains.js
class Domains {
    constructor (options = {}) {
        ....
    }
}
module.exports = Domains;

// Factory.js
const Domains = require('./Domains');
module.exports = {
   foo: async () =>{

      .... async stuff ...

     return new Domains();
    }
};

when I run main.js I get

(node:1816) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: Domains is not a constructor
warning.js:18
(node:1816) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Debugging, I found that in Factory.js when it requires Domanis.js const Domains = require('./Domains'); it returns an empty object.

Looking around on internet I found that it happens when there are a circular dependencies between modules (Require returns an empty object) but It doesn't seem the case here.

Any idea?

like image 864
Gappa Avatar asked Mar 06 '23 09:03

Gappa


1 Answers

Finally, I got the the issue's origin. The empty object was due to a circular dependency derived by another require that was inside Domains.js

// Domains.js
const another_module= require("circular_dep_creator");
class Domains {
    constructor (options = {}) {
        ....
    }
}
module.exports = Domains;

// circular_dep_creator.js
const factory = require ('./Domains/Factory');
...
another stuff

So, this causes a circular dependency that creates an empty object

like image 139
Gappa Avatar answered Mar 07 '23 21:03

Gappa