Creating A Simple HTTP Server In node.js

node.js is still considered to be the new mischievous kid on the block.

node.js is an event-driven JavaScript platform. It is a light-weight and efficient framework. Its efficiency in terms of speed and and high throughput has been derived due to its non-blocking (aka Asynchronous) I/O model.

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/

Getting Started

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:

  1. Line 1: Declare a variable and require HTTP module to instantiate the server.
  2. 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.
  3. 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
  4. 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:
Hello World

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

Add a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.