I recently started to learn node.js + Express and found it very interesting.
I have read many postings about sharing variables in routing, and many of them were using module.exports and exports.
I decided to make a function to setup a local variable
routes/test.js
var db;
exports.setup = function(_db){
db = _db;
};
exports.doit = function(req, res){
db.get("testToken", function(err, result) {
console.log("err: " + err);
console.log("result: " + result);
res.send("respond with a resource");
});
};
app.js
var redis = require("redis");
var db = redis.createClient();
var test = require("./routes/test.js");
test.setup(db);
// configuration...
app.get('/', test.doit);
Is it ok to do things like this?
I want to make sure that I don’t make db connections more than once, and sharing vars was the only way I could think of…
Can you make any suggestions?
Thank you!!
That should work fine. Though, you might consider separating “setup” from the “routes.”
Since
dbis always the same value, you can use Express 3’sprototypeobjects to attach it to thereqand/orresobjects in all routes:routes/test.jsapp.jsThough, you can also define “setup” as a custom middleware: