Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Can Node.js module caching be used to create globally accessible singletons?

Can Node.js module caching be used to create globally accessible singletons?

Problem

After splitting my project up into many OO classes I am having to pass a reference to my Model instance (contains Mongoose models and schema) through multiple constructors.

Would it be bad practice to create an instance of the Model class inside the model.js module and then require this model.js module everywhere I need it?

Something like this:

Model = function () { ... }

module.exports = new Model();

This would rely on Node's module caching to allow the same Model instance to be shared between files, like having a global singleton.

Or should I explicitly pass dependencies through constructors?

Problem courtesy of: vaughan

Solution

No, it's not a bad practice. In fact, many people do it this way.

Solution courtesy of: Pavan Kumar Sunkara

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Can Node.js module caching be used to create globally accessible singletons?

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×