Reputation: 605
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.
Upvotes: 0
Views: 2519
Reputation: 311835
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.
Upvotes: 1