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
}