2

file structure is

-src
--Visitor
---visitor.model.js
---Sessions
----session.model.js

In visitor.model.js file

const {Sessions} = require('./Sessions/session.model');
const Visitor = {};

Visitor.visitorFunc = () => {


}

Sessions.sessionFunc();

module.exports = {Visitor: Visitor};

In session.model.js file

const {Visitor} = require('../visitor.model.js');

const Session = {};

Sessions.sessionFunc = () => {

}

Visitor.visitorFunc();

module.exports = {Session: Session};

when I do imports like this in Visitor file Session is undefined. What is the reason for that.. Is it calling import recursively ?

PrashanD
  • 2,643
  • 4
  • 28
  • 58
noone
  • 6,168
  • 2
  • 42
  • 51

4 Answers4

3

Circular dependencies are allowed in node

https://nodejs.org/api/modules.html#modules_cycles

When main.js loads a.js, then a.js in turn loads b.js. At that point, b.js tries to load a.js. In order to prevent an infinite loop, an unfinished copy of the a.js exports object is returned to the b.js module. b.js then finishes loading, and its exports object is provided to the a.js module.

Since Session and Visitor sounds like database models with an M:N relationship circular dependencies are the way to go (e.g.: Join query)

How to deal with cyclic dependencies in Node.js

Node.js Module.Exports Undefined Empty Object

But it would be less messy to avoid them if you can.

PrashanD
  • 2,643
  • 4
  • 28
  • 58
1

As @prashand above has given the reasons you would have to do imports and calling imported functions after exporting current module.. above example is working with a slight change as follows

const Visitor = {};

Visitor.visitorFunc = () => {

  console.log('hello from visitor model');
}


module.exports = {Visitor: Visitor};
// import session.model after exporting the current module

const {Session} = require('./Sessions/session.model');

// then call the required function
Session.sessionFunc();
noone
  • 6,168
  • 2
  • 42
  • 51
1

Simply just use exports.someMember = someMember instead of module.exports = { someMember }.

Pankaj Shinde
  • 3,361
  • 2
  • 35
  • 44
-1

Your visitor.model.js file is outside the Sessions directory. In order to import session.model.js you need to give absolute path to that file. So your require statement should be like this

const { Sessions } = require('../Sessions/session.model.js');
Siddharth Sinha
  • 578
  • 2
  • 15
  • 35