Wednesday, October 23, 2019

Pattern to solve circular dependencies in node,

This is an useful pattern to avoid circular dependencies while requiring other files in node.

Circular dependencies manifest when a require returns an empty object: "the circular dependency means that other code receives an incomplete module object"

The solution is to 'augment' the exports instead of replacing it. 
So, if another module got a reference to the exported members they are eventually completed.

//requires at the beginning, as usual
//.. 


const PublicMethods = {
 method1: () => {},
 method2: (x) => {...},
 ...
]; 

// -- private & other methods
... 
...

//augment the exports at the end of the file:
Object.assign(module.exports, PublicMethods);



3 comments:

  1. Amazing piece. There are so many lessons to be learned from thisUSA Dedicated Server. Thank you for sharing this kind of work author.

    ReplyDelete
  2. Wow! fantastic blog post, you. Sincere thanks for doing that. The knowledge provided by this site about Another Step Forward for Dedicated Web Server in Market is quite helpful. If you're looking for the quickest and most affordable Dubai VPS Server, contact us for more details about our offerings.

    ReplyDelete
  3. amazing blog The quality and depth of your blog posts are greatly appreciated. It's a great resource for bloggers generally. You do more than just outline the steps involved in starting a blog; you also provide guidance on selecting a suitable topic. If you want to build and create websites that last for years and adapt to your business's changing needs, you need a solid WordPress platform. As an additional resource, check out Why You Should Choose WordPress for Your Website?

    ReplyDelete