简体   繁体   中英

node.js - accessing required variables from other files

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM