node.js - accessing required variables from other files

Problem

I have a node application that is made mainly of two files, the "app.js" main one, and a "router.js". In the app.js file I am requiring all the files I need, for example, the Redis client.

I am a total newbie and I am trying to figure out how to "access" the newly created variable "client" on router.js:

//app.js file
var redis   = require("redis"),
    client  = redis.createClient(9981, "herring.redistogo.com");

app.get('/', routes.index);



//router.js file
exports.index = function(req, res){
 client.get("test", function(err, reply) {
   console.log(reply.toString());
 });
};

I obviously get a "client is not defined", because it cannot be accessed from that router.js file. How do I fix this?

Thanks in advance.

Problem courtesy of: john smith

Solution

Put the Redis client object in its own file that the other files require:

// client.js file
var redis = require("redis"),
    client = redis.createClient(9981, "herring.redistogo.com");
client.auth("mypassword");
module.exports = client;

//router.js file
var client = require("./client");
exports.index = function(req, res){
 client.get("test", function(err, reply) {
   console.log(reply.toString());
 });
};

Required modules in node are only loaded once, and each file that requires the module gets the same object so they all share the single Redis client object.

Solution courtesy of: JohnnyHK

Discussion

There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.