Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

weird behavior of module require in nodejs

It's hard to explain so I will reproduce the code.

I have two class files.

Business.js

const Street = require("./Street");

module.exports = class Business {};

Street.js

const Business = require("./Business");

module.exports = class Street {
  constructor() {
    console.log(Business);
  }
};

and index.js file

const Street = require("./Street");

const street = new Street();

when I run index.js (node ./index.js), it log [Function: Business] as expect,

but when I require Business.js in index.js file like below, log message change, it log empty object {}.

index.js

const Business = require("./Business");
const Street = require("./Street");

const street = new Street();

I don't understand why require Business in index.js effect log message in Street.js file.

try it out codesandbox.

Edit node module misbehavior

like image 492
Kyaw Kyaw Soe Avatar asked Mar 17 '26 18:03

Kyaw Kyaw Soe


1 Answers

Seems like there is a circular dependency. Ideally a module should not depend on a module that depend on that module.

Since your Business.js module depend on Street.js module and Street.js module depend on Business.js module (which is called a circular dependency) you are getting this "weird behavior".

Any restructure that avoid circular dependency will be okay, like moving both classes to the same file (just a suggestion, you may want to use another way as your use case and coding practices).

class Street {
  constructor() {
    console.log(Business);
  }
}

class Business {}

module.exports = {
  Street,
  Business
}; 

try it out codesandbox.

Edit node module misbehavior

like image 107
Janith Avatar answered Mar 20 '26 06:03

Janith



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!