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
In JavaScript, variables can be accessed from another file using the <script> tags or the import or export statement. The script tag is mainly used when we want to access variable of a JavaScript file in an HTML file. This works well for client-side scripting as well as for server-side scripting.
The arguments available to an Express. js route handler function are: req - the request object. res - the response object.
To make a global variable, just declare it without the var keyword. (Generally speaking this isn't best practice, but in some cases it can be useful - just be careful as it will make the variable available everywhere.) Here's an example from visionmedia/screenshot-app. file app.js: /** * Module dependencies.
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
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.js
var db
var redis = require('redis')
exports.connect = function() {
if (!db) db = redis.createClient()
return db
}
exports.disconnect = function() {
redis.quit()
db = null
}
// index.js
var dbHelper = require(.'/db')
var db = dbHelper.connect()
// whatever other file
var dbHelper = require(.'/db')
var db = dbHelper.connect() // won't connect twice
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With