0

There is a generic structure of nodejs callback functions :

function(req,res){
  //handle callback
}

I just want, callback should work correctly even if sometimes i write in mistake (res, req)

Given mixture of req or res, how do i find which one is actually request and which one is response.

codeofnode
  • 18,169
  • 29
  • 85
  • 142
  • 1
    According to the API, `req` goes before `res`, regardless of how you really name them. You should just avoid swapping in your functions. – E_net4 Apr 07 '15 at 13:12

2 Answers2

4

req is an IncomingMessage object and res is a ServerResponse object.

So check for unique properties on each, for example if the particular object has a writeHead() function, then it's the response object.

You may also be able to use instanceof to check: res instanceof http.ServerResponse.

mscdex
  • 104,356
  • 15
  • 192
  • 153
3

Functions in JavaScript are not programmatically prototyped by parameter names. The length property of a function only provides the number of parameters specified in the definition:

var fn = function (one,two,three) { return "x"; };
console.log(fn.length); // 3

Although there are ways to retrieve these names (see this question), usually procedures simply ignore how you name the parameters of your functions/closures, and instead assume that you are following the proposed API.

For this reason, it remains as the best practice to pay attention to the API and name parameters accordingly. In a Node.js HTTP request listener, the request comes always before the response (it is documented and many examples are available). As mentioned by other answers, you can dynamically check whether the request is an http.IncomingMessage or whether the response is an http.ServerResponse, but it seems to me that you can avoid introducing an overhead just with proper naming.


With that said, given the variables req and res, it is easy to make a check at the top of a function body, like the code below. However, do note that this would only be remedying what can be prevented by just following the API contracts, and as thus I cannot recommend it (unless you really want to make functions with a more flexible API).

function(res,req) {
  if (req instanceof http.ServerResponse) {
    // wrong order, swap.
    var t = req;
    req = res;
    res = t;
  }
  // handle request
}
E_net4
  • 27,810
  • 13
  • 101
  • 139