3

I am getting my hands on node.js and I am trying to understand the whole require/exports thing. I have the following main app.js file:

/app.js

var express  = require('express'),
    http     = require('http'),
    redis    = require('redis'),
    routes   = require('./routes'),

var app    = express(),
    client = redis.createClient();


// some more stuff here...
// and my routes

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

then, I have the routes file:

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

I can of course use the client object on my app.js file, but how can I use the same object in my routes?

2 Answers 2

1

Since req and res are already being passed around by Express, you can attach client to one or both in a custom middleware:

app.use(function (req, res, next) {
  req.client = res.client = client;
  next();
});

Note that order does matter with middleware, so this will need to be before app.use(app.router);.

But, then you can access the client within any route handlers:

exports.index = function(req, res){
  req.client.get(..., function (err, ...) {
    res.render('index', { title: 'Express' });
  });
};
Sign up to request clarification or add additional context in comments.

3 Comments

can I pass it in another object instead of attaching it to req or res?
@johnsmith Not really. Express isn't passing any other objects, so including one requires closures, which is what Problematic suggested. Attaching to req and res is a rather common practice and is how most Connect middleware work (Express being an extension of Connect). You can also find a real-world example of this type of attachment in the npm-www project, the source behind npmjs.org.
that's pretty cool, thank you! I think iI'll stick with this as it seems a more elegant solution to me
1

The easiest way is to export a function from your routes file that takes a client, and returns an object with your routes:

exports = module.exports = function (client) {
    return {
        index: function (req, res) {
            // use client here, as needed
            res.render('index', { title: 'Express' });
        }
    };
};

Then from app.js:

var client = redis.createClient(),
    routes = require('./routes')(client);

1 Comment

is that the only way to do it? I'm not an expert at all so I have no idea what I am saying but that surely looks kind of complicated! :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.