I am using redis to store sessions in my project.
In app.js
var client = redis.createClient();
client.on('error', function (err) {
console.log('could not establish a connection with redis. ' + err);
});
client.on('connect', function (err) {
console.log('connected to redis successfully');
});
In my routes.js
files i have to get all information from redis, so i am using the following:
var client = redis.createClient();
client.on('error', function(err){
console.log('Something went wrong ', err)
});
But everytime its connecting to redis. How can i connect redis once in my app.js
and use it everywhere. please suggest ideas. Thanks in advance.
EDIT
app.js
module.exports.client = client;
routes.js
var client = require("../app.js").client;
client.hgetall();
But i am receiving error
TypeError: Cannot read property 'hgetall' of undefined
In app.js
var client = redis.createClient();
client.on('error', function (err) {
console.log('could not establish a connection with redis. ' + err);
});
client.on('connect', function (err) {
console.log('connected to redis successfully');
});
module.exports = { client }
In routes.js
var { client } = require('./app');
client.on('error', function(err){
console.log('Something went wrong ', err)
});
(Assuming app.js
and routes.js
are in same level of directory)
EDIT: fixed few typo
app.js
const redis = require('redis'),
redisClient = redis.createClient(6379, '127.0.0.1');
const http = require('http');
const REDIS_USER_DATA_INDEX = 2;
redisClient.select(REDIS_USER_DATA_INDEX);
module.exports.client = redisClient;
routes.js
const app = require('./app');
app.client.on('connect', function () {
console.log('redis connected');
console.log(`connected ${app.client.connected}`);
}).on('error', function (error) {
console.log(error);
});
I hope this will resolve your issue. Thanks
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.