node.js is still considered to be the new mischievous kid on the block.
Along with many things Node.js can be used as a web server. This tutorial explains how to create a simple HTTP server with node.js which gives a 200 status OK page with some content.
Please note: You must need node.js installed to start with this tutorial. You can download the flavor of node.js of your choice from here https://nodejs.org/en/download/
Once you have installed node.js, its time to get started.
First lets create a directory.
$ mkdir myNodeApp
Now create a file called server.js within the new directory. In my case the it is myNodeApp
The code for server.js is as follows:
Breakdown and explanation of the code:
- Line 1: Declare a variable and require HTTP module to instantiate the server.
- Line 2: Create a new web server object. Add a function to the server object which will handle request and response. The requests and response passed to the function as parameters.
- Line 3 and 4: When a request is generated on the server, response header defined here will be sent. In this case, the response header is sent as:
- 200: HTTP Status code set to OK
- Content-Type: Content type of the page set to text/plain
- Line 5: This is the termination signal to the server determining that all the response headers and body is send. The end signal is accompanied with some data to output to the browser. In this case it is:
Optionally the encoding can also be defined to res.end()
- Line 6: Listen to the server IP address which will serve the requests. The IP address must be accompanied with the port number. In this case, the server is running on localhost loopback IP (127.0.0.1) and port number 3000
- Line 7: Outputs a message on successful start of the server on the console.
Once the codes for server.js are set, its time to start the server. To do this, change your directory to the application directory and run with node command as follows: –
$ cd myNodeApp
$ node server.js
As soon as the server is successfully started you will see output from console.log() specified on line 7 in the console