TBE
TBE

Reputation: 1133

Object doesn't seem to load with all of its properties. - Node.js

I have two js files on my node server that require each other. both have objects that are exposed via the module.exports mechanism.

1st file is located under bl/commands.js and uses:

var smUtil = require('./../utils/smUtil');

2nd file is located under utils/smUtil.js and uses:

var commands = require('./../bl/commands');

When a function runs from smUtil.js and uses some properties of commands.js it seems like command is an empty object and the import was not successful.

Here is the catch, when i remove the require of smUtil form inside commands.js everything works, which makes me think that i'm doing a newbe mistake.

Any thoughts?

Upvotes: 0

Views: 67

Answers (2)

TBE
TBE

Reputation: 1133

The specific solution which solved my problem was to place var smUtil = require('./../utils/smUtil'); Underneath the module.exports inside commands.js.

However i feel like this solution is not the best one out there.

Thanks to the author of: coderwall.com/p/myzvmg/circular-dependencies-in-node-js

Upvotes: 0

zahreelay
zahreelay

Reputation: 1742

Node.js documentation about circular dependencies

You are absolutely right that empty objects are returned.

To Quote Node.js documentation

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.

A solution could be to create a separate file to require both the files there and instantiate that file to avoid the circular dependency.

Upvotes: 1

Related Questions