Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Passing a value to a Node js module for Express routes

Passing a value to a Node js module for Express routes

Problem

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?

Problem courtesy of: rob_hicks

Solution

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) {
            // ...
        };
    };
};
Solution courtesy of: Vadim Baryshev

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Passing a value to a Node js module for Express routes

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×