0

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.

john smith
  • 565
  • 1
  • 10
  • 20

1 Answers1

1

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.

JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
  • it is important to underline that I also need to do the following after createClient(): `client.auth("mypassword");` – john smith Nov 24 '12 at 15:12
  • ouch, I'm getting a Cannot find module './client' ... Although I have created the file in the root directory. Could it be because the router.js is in a subdirectory? – john smith Nov 24 '12 at 15:21
  • @johnsmith Yes, the relative path to a required module must be correct. Sounds like it should be `require('../client');` in your case. – JohnnyHK Nov 24 '12 at 15:28