Node.js pass variable to route

I have very simple node.js noob question. How do I pass a variable to an exported route function?

Routes file

exports.gettop = function(n, req, res) {
  console.log(n);
  res.send(200);
};

Server file

app.get('/api/v1/top100', routes.gettop(100)); 

Error: .get() requires callback functions but got a [object Undefined]

For your example, you want to create a new function that will close around your value of n. In your case, you are executing gettop and passing the returned value to express as your route, which means gettop needs to return the route handler.

exports.gettop = function(n){
    return function(req, res) {
        console.log(n);
        res.send(200);
    };
};

As your code looks like you're using express you can use express app locals and express result locals to pass variables to your route. While the other answers propose working solutions I think that it's less obtrusive to use express mechanisms to set these variables.

With response locals (See Express API reference) you first have to set a variable somewhere in a middleware or route. I'll show the middleware approach

app.use(function(req,res, next) {
  res.locals.top = 200;
});

then in your route you can access this property via res.locals.variablename

exports.gettop = function(req, res) {
  console.log(res.locals.top);
  res.send(200);
};

In case you want to make these settings application wide a better approach is to use app locals (See Express API reference)

To set an app locals variable you can use

app.locals.top = 100;

To access this variable from your route use

exports.gettop = function(req, res){
  console.log(req.app.locals.top);
  res.send(200);
};

As an alternative to loganfsmyth's (very valid!) solution, you could leave your gettop function as-is and create a partial function:

app.get('/api/v1/top100', routes.gettop.bind(null, 100));