Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a value to a Node js module for Express routes

I want to pass the environment for Express to a routing module for Express. I want to key off of whether Express is running in development or production mode. To do so, I'm guessing I need to pass app.settings.env somehow to a routing module.

My routing module exports a function for each route. So:

app.get('/search', web.search);

Based upon a previous stackoverflow post, i have tried this:

var web = require('./web')({'mode': app.settings.env});

But node throws an type error (object is not a function).

I'm new to Node and Express. Can I pass a value to an express route and if so, how?

like image 853
rob_hicks Avatar asked Mar 14 '12 19:03

rob_hicks


1 Answers

If you web.js looks like this:

module.exports.search = function(req, res, next) {
    // ...
};

module.exports.somethingOther  = function(req, res, next) {
    // ...
};

then by calling

var web = require('./web')({'mode': app.settings.env});

you try to use object (module.exports) as function. Type error here.

You need to convert module.exports to function to pass parameters to it. Like this:

module.exports = function (env) {
    return {
        // env available here
        search: function(req, res, next) {
            // ...
        },

        somethingOther: function(req, res, next) {
            // ...
        };
    };
};
like image 150
Vadim Baryshev Avatar answered Sep 25 '22 15:09

Vadim Baryshev