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

Is there a better way to structure global variables in Node.js?

Is there a better way to structure global variables in Node.js?

Problem

Trying to understand what would be the best way to Structure some variables. For example in my Node.js Express app, I have the following in app.js:

var poolModule = require('generic-pool');
global.pools = {
 /* ... */
};

Where pools is my global variable that keeps track of MySQL and Redis pools. I am also wondering if I can do the same with actual Redis and MySQL objects (and maybe configs variable) so I don't have to require them all over the app. And since they are going to be used the most.

Is this bad practice, and if yes, what's a better way to structure this kind of code?

Edit: added global.

Problem courtesy of: Jon Derring

Solution

If you require a file you are actually always requiring the same object. So that means you can do:

module.exports = {
  // same object for everybody that requires me
};
Solution courtesy of: Pickels

Discussion

View additional discussion.



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

Share the post

Is there a better way to structure global variables in Node.js?

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×