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 c
Solution 1:
I really liked Jamund's solution, but I would extend the concept to this:
// db.jsvar redis = require('redis');
module.exports = redis.createClient();
// index.jsvar db = require(.'/db')
// whatever other filevar 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
Solution 2:
Just call this at the top of your files. Requires are in a shared space, so you can re-require the file multiple times and it will always reference the same version. If you want to be fancy you can create your own db module that does something like this, to prevent double creating clients:
// db.jsvar db
var redis = require('redis')
exports.connect = function() {
if (!db) db = redis.createClient()
return db
}
exports.disconnect = function() {
redis.quit()
db = null
}
// index.jsvar dbHelper = require(.'/db')
var db = dbHelper.connect()
// whatever other filevar dbHelper = require(.'/db')
var db = dbHelper.connect() // won't connect twice
Solution 3:
You can either create an app global and hang the vars you want to share off that or you can use an initializer function in your routes file
f.e.
// app.jsvar app = express.createServer()
, db = require('redis').createClient();
require('./routes').with(app, db);
// routes.jsmodule.exports.with = function(app, db) {
app.get('/',function(r,s) { s.end('Sweet');});
}
Post a Comment for "How To Access Variables Declared In Main App.js In Separate Route Files In Node.js Express 2.5.5?"