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

node.js passing variables

node.js passing variables

Problem

I am looking for some direction here from some seasoned node.js programmers. The biggest issue I am running into is passing around variables into separate modules. For example in my server.js I have the following:

var db = mongoose.createConnection('localhost','test');

Now I am not running my routes inside of the server.js file they are separated into there own files. So for a blog example it might be like this:

app.get('/blog/post/:id',function(req,res){
    //do something here
}

Now this is where the problem comes in. I do not want to have to setup a database connection in each of my routes and not to mention I would think that it would make a ton of connections. How do I handle this, is there a sample "REAL WORLD" application out there because I cannot seem to find anything about this and I know people have had to have this problem before. I know that node caches the modules but I cant imagine that it would cache the connection given it was in its own module. I created a config module that just holds the site config so requiring this where I need it is not a problem. I imagine there are other things that I am gonna wanna do this with so it would be best to figure this out now.

Any help is appreciated.

Problem courtesy of: ngreenwood6

Solution

Here's what I do in my real world app.

I have a module named redis (that's the database I'm using). It contains the following code:

var store;

exports.store = store = redis.createClient(config.port, config.url);

So, I can directly access the client, if I need to. I almost never do that. The same module contains code like this:

exports.getData = function(dataID, callback){

    var key = DATA_STORE_PREFIX;

    try{
        store.hget(key, dataID, callback);
    } catch(err){
        callback(err);
    }
}

I use this by including the redis module in one or more route modules and calling it like this:

var db = require('redis');

db.getData('someData', function(err, result){
    console.log(result); // real world code goes here!
});

The node module system takes care of the rest.

Solution courtesy of: Waylon Flinn

Discussion

View additional discussion.



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

Share the post

node.js passing variables

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×