David Jones
David Jones

Reputation: 10219

Node + Express: How do the req and res variables have global scope without causing collisions?

It seems that the req and res variables have global scope in Express (e.g. these variables are accessible regardless of the function scope). How is this achieved without causing collisions between simultaneous clients?

Upvotes: 2

Views: 1595

Answers (1)

Daniel
Daniel

Reputation: 38781

They do not have global scope.

Route

The route takes a handler function for each route. That route is passed the req and res objects.

app.get('/my-route', myHandler);

Handler

Your handler receives those objects and uses them.

exports.myHandler = function(req, res) {
    res.send("Hello world");
);

Closures

When you make a database call (or any other io bound call) you pass it a callback. The req and res objects live in that callback as a closure.

exports.myHandler = function(req, res) {
  var weekday = req.query.weekday || "today";
  db.getWeather(weekday, function(err, result) {
    // `res` here is a closure
    if(err) { res.send(500,"Server Error"); return; }
    res.send(result);
  });
};

More about closures: How do JavaScript closures work?

Upvotes: 6

Related Questions