Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
159 views
in Technique[技术] by (71.8m points)

javascript - How to access variables declared in main app.js in separate route files in node.js Express 2.5.5?

I just started using a new version of Express (2.5.5) that by default creates a ./routes directory along with ./views and ./public

Inside of routes there is a index.js file which contains:

/*
 * GET home page.
 */

exports.index = function(req, res){
  res.render('index', { title: 'Express' })
};

by default (after running express from the commandline) and this is the routes section in the main app.js:

// Routes

app.get('/', routes.index);

I've set up a variable for a redis client in the main app.js:

var redis = require('redis'),
    db = redis.createClient();

and I was wondering how I could access the methods of db (and whatever other modules I require in app.js) in the files contained in ./routes

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I really liked Jamund's solution, but I would extend the concept to this:

// db.js
var redis = require('redis');
module.exports = redis.createClient();

// index.js
var db = require(.'/db')

// whatever other file
var db = require(.'/db')
// do something with db
db.disconnect();

both db on index and other file would get the same instance of the redis client


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...