Claude Tan
Claude Tan

Reputation: 399

What's the 'response' argument in these node.js code?

This is a node.js client. The 'response' of the callback function confuses me. I changed it into some other meaningless words such as 'haha' or 'hello' and it still works.

I vaguely know that it is the response from the server, but I think the server can't send a 'response' object or instance to the client.

What is this 'response' and where is it from?

Besides, does the 'response' contain the 'data' in the code?

var http = require('http');
var options = {
   host: 'localhost',
   port: '8081',
   path: '/index.html'  
};
var callback = function(response){
   var body = '';
   response.on('data', function(data) {
      body += data;
   });

   response.on('end', function() {
      console.log(body);
   });
}
var req = http.request(options, callback);
req.end();

Here is the server code.

var http = require('http');
var fs = require('fs');
var url = require('url');

http.createServer( function (request, response) {  
   var pathname = url.parse(request.url).pathname;       
   console.log("Request for " + pathname + " received.");       
   fs.readFile(pathname.substr(1), function (err, data) {
      if (err) {
         console.log(err); 
         response.writeHead(404, {'Content-Type': 'text/html'});
      }else{             
         response.writeHead(200, {'Content-Type': 'text/html'});             
         response.write(data.toString());       
      }
      response.end();
   });   
}).listen(8081);

console.log('Server running at http://127.0.0.1:8081/');

Upvotes: 0

Views: 674

Answers (1)

rsp
rsp

Reputation: 111374

The names are not important. What is important is the order of the parameters and what is passed there.

In this case the first parameter is getting an instance of http.IncomingMessage while the second parameter is getting an instance of http.ServerResponse - see:

For convenience those can be called request and response but they can be called however you like. I often see req and res for example.

It's the as with calling ordinary functions. So this:

function divide(a, b) {
    return a / b;
}

is the same as:

function divide(c, d) {
    return c / d;
}

When you have a callback that gets a request as the first parameter and the response objects as the second parameter, it doesn't matter how you call it internally. The point is that one of those objects is passed to your first parameter (no matter how it's named) and the second one is passed to the second parameter.

The same is true for naming the error parameter err or error:

asyncFunc(param, function (err, data) {
    if (err) {
        console.log('Error:', err);
    } else {
        console.log(data);
    }
});

this is the same as:

asyncFunc(param, function (error, something) {
    if (error) {
        console.log('Error:', error);
    } else {
        console.log(something);
    }
});

Upvotes: 1

Related Questions