Vikas Kumar Vikas Kumar - 1 month ago 6
Node.js Question

What is client, path and data in this code?

I'm learning Node.js I have created server and client .js files but I don't understand few things. For example, in the webserver.js file, I don't know what is the use of

pathname
. Similarly, in the
client.js
file, what are
data
and
path
?

If you think I should read about the basics of it, please provide me a useful link if you can. I tried to find but didn't work.

webserver.js

var fs=require('fs');
var url=require('url');
var http=require('http');
http.createServer(function(request, response){
var pathname=url.parse(request.url).pathname;
console.log("Pathname: "+pathname+"Request.url: "+request.url);
fs.readFile(pathname.substr(1), function(err, data){
if(err){
console.log("Error reading.");
response.writeHead(400, {'content-type' : 'text/html'});
}else{
response.writeHead(200, {'content-type' : 'text/html'});
response.write(data.toString());
}
response.end();
});
}).listen(8081);
console.log("Server is running.");


client.js

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("Data received.");
});
}
var req=http.request(options, callback);
req.end();


The original code souce is here: Code

Answer

pathname is the path requested to the http server. The example pathname for this question is /questions/40276802/what-is-client-path-and-data-in-this-code. The path in client.js is the same deal.

You can find documentation on parsing the URL into the pathname from the Node.js docs: https://nodejs.org/api/http.html#http_message_url

Node's HTTP client uses streams, which emit several events. data is called with a buffer, which you usually will add to an array then concat later (as the code does). end is called when all buffers are sent.

You can find documentation on handling events from streams from the Node.js docs: https://nodejs.org/api/stream.html#stream_class_stream_readable

Comments