Sub*_*raj 5 javascript redis node.js
我正在使用 redis 在我的项目中存储会话。
在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');
});
Run Code Online (Sandbox Code Playgroud)
在我的routes.js文件中,我必须从 redis 获取所有信息,因此我使用以下内容:
var client = redis.createClient();
client.on('error', function(err){
console.log('Something went wrong ', err)
});
Run Code Online (Sandbox Code Playgroud)
但每次都是连接到redis。我怎样才能在我的系统中连接一次redisapp.js并在任何地方使用它。请提出想法。提前致谢。
编辑
app.js
module.exports.client = client;
routes.js
var client = require("../app.js").client;
client.hgetall();
Run Code Online (Sandbox Code Playgroud)
但我正在收到error
TypeError: Cannot read property 'hgetall' of undefined
Run Code Online (Sandbox Code Playgroud)
在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 }
Run Code Online (Sandbox Code Playgroud)
在routes.js
var { client } = require('./app');
client.on('error', function(err){
console.log('Something went wrong ', err)
});
Run Code Online (Sandbox Code Playgroud)
(假设app.js和routes.js位于同一级目录中)
编辑:修复了一些错字
| 归档时间: |
|
| 查看次数: |
7235 次 |
| 最近记录: |