Creating a Server in Node.js
From the previous article we got to know how to read and write files in Node.js. This article will help you to get to know about Clients and servers in Node.js
First lets look at what client and server really means. When we browsing internet by using chrome or any other browser we request for some data. This is where the client send its request to get a response particular to the clients request. Then the server acts on the request of the client and send a response which we finally see as our search results.
Basically considering the client ad server each computer can be uniquely identified by using their IP addresses.So when communicating they need to get connected through the IP addresses.So the information is shared using different protocols like http. This transferring data is called TCP where the data is transmitted through data packets from server to client. Using Node.js, we can use the same functionality to communicate with computers.
Creating a Basic Server
To create a Server we need to get one of the core modules in Node which is called http. As we did in previous articles, require the http module to your file.
Now create a method to build a server.
var http=require('http');
var server = http.BuildServer(function(req,res){});//function with request and respond variables
Inside the function we should build a header to serve as the response.
var server = http.createServer(function(req,res){
res.writeHead(200,{'Content-Type': 'text/plain'});
res.end('Hello World');
});
Next build a request to listen the port
server.listen(3000,'127.0.0.1');
console.log('Hey you are now listening to port 3000'); // just to show that you are listening
In here 3000 is the port number and 127.0.0.1 is the address of the localhost which means it listen to the Localhost
Now run the command line.Then type 127.0.0.1:3000 in your web browser
Comments
Post a Comment