How to Instantiate a Web Server in Node js

|
| By Webner

How to Create and Access a Web Server in Node js

To access web pages of any web application we need a web server. The web server handles all http requests for the web application.

Node.js framework is mostly used to create server based applications. Node.js doesn’t use HTTP server like Apache or Nginx. Instead Node js can easily be used to create its own web server. It has a built In HTTP module, which allows to create HTTP server, that listens ay a server port and gives a response back to the clients.

We need to use require directive to load Node.js http module.

E.g:- var http = require('http');

Then need to create a server which will listen to client’s requests similar to Apache HTTP Server.

http.createServer(function (req, res) {  }
// This  function will  execute each time the server receives a new request.

The above function takes two arguments, request and response. The request object contains information regarding the client’s request, such as the URL, HTTP headers etc. Similarly, the response object is used to return data back to the client.

Steps to create Server:-

1)Make sure if you have node.js installed properly.
2)Create a new folder for node.js project (E.g:-NodeJsNewApp).
3)Create the new node.js file named “test.js”.
4)Write the following code in that file

var http = require('http');    // call http library 
http.createServer(function (req, res) { 	// Create  server using http  library                                                                                                                                                                          
      	  res.writeHead(200, {'Content-Type': 'text/html'});    // Set the content header 
      	 res.end('Server created successfully');    // Send string to the response
}).listen(7070);             // Make server listen on port 7070

5) Node.js file must be instantiated in the command line interface.

Firstly navigate to the folder where .js file exist using CLI.

cd D:\NodeJsNewApp.  

Now write node test.js and hit enter:

D:\NodeJsNewApp>node test.js.

After this, your system will work like as a server. If anyone tries to access our computer on port 7070(http://localhost:7070), he / she will see a “Server created successfully” message in the browser.

E.g:-
Web Server in Node js

Leave a Reply

Your email address will not be published. Required fields are marked *