Create a Web Server using Node.js

Posted by: Mahesh Sabnis , on 10/21/2015, in Category Node.js
Views: 20491
Abstract: Using Node.js to create a web server and provide some basic functionality for request processing

In traditional Web Servers, there is usually a separation between servers used for request processing and for those that hold the business logic of the application. This is a common scenario in almost all server side technologies like ASP.NET, PHP, etc. Traditional web servers need configuration e.g. using web.config file where we set the expected behavior for request processing on the server-side.


Where does Node.js fit?

Node.js is a simple platform for building fast and scalable server apps using JavaScript. Node.js is shipped with several core modules by default packaged and managed using NPM (Node Package Manager). These modules have their own responsibility and behavior. Using one of the modules we can create a web server, customize it and deliver requested contents. The important part here is that we can do all this at code level. We can create a web server using the important http module.

If you are new to Node.js, get started over here Node.js Tutorial Series - Getting Started

Prerequisites for the implementation

To implement a web server, we will need the following resources to make things simpler for us:

Any IDE of your choice like Sublime Text or Visual Studio Code

You also need NTVS (Node Tools for Visual Studio). Here’s an entire article on the same Node Tools for Visual Studio.

Node.js Web Server Implementation

The implementation here uses Visual Studio Code. This is an extremely lightweight IDE for building and debugging modern web and cloud applications and is available for free on the Windows, Mac OSX and Linux platform.

Step 1: Create a folder on your drive (say E:\) with the name VSCodeWebServer. Alternatively, you can also use Visual Studio Code to create a new folder. We will be using this to store our application files. Open Visual Studio Code. Open the VSCodeWebServer folder using File > Open Folder Option. Once the folder is open, the option for creating new file will be displayed as an icon as shown in the following image.


Step 2: Add a new file of the name app.js in this folder using Visual Studio Code.

Step 3: To use code intellisense, VS Code uses Typescript definition files for example node.d.ts. The same metadata is also used to warn you if you are not using an API correctly. We can install this using following steps.

- Open the Node Command prompt (CTRL+Shift+C ).

- Navigate to the VSCodeWebServer folder.

- Run the following commands from this path

npm install -g tsd

Here TypeScript Definition Manager (TSD) makes it easy to search the tsd files for the current folder workspace.

Run the following command for the required intellisense for the Node and its modules.

tsd query node --action install

This will provide an easy experience for Node module coding.

Step 4: To create a web server we need http module. This module provides createServer() function which returns a new instance of the http.server. This instance emits several events for managing request, server connections, listener, response, timeout, close, etc. In the following code, we will be loading http module and set content types in header along with the response. Add the following code in the app.js.

var http = require('http');
var server = http.createServer(function (req, resp) {
    resp.writeHead(200, { 'Content-Type': 'text/html' });
    resp.end("Hello, this is the test web server created");
console.log('Server Started');

The above code performs the following operations. The numbers listed below matches with the comments numbers in the code.

1. Loads the http module. This is the default module available with the Node installation.

2. A http server is created using createServer() function. This accepts requesthandler callback, representing request and response.

3. writeHead() sends the response header to the request along with the status code. The second parameter is the response header. This method must be called once on a request message and before the response end().

4. end() ensures that the all the headers and the message body is sent. This represents the message completion. The parameter to this method is the data being sent.

5. listen() represents that the request messages are being accepted on the port specified, and optionally on the hostname.


Step 5: Right-Click on app.js and select Open in Command Prompt option. This will show the command prompt from where we can run the application.


Step 6: Execute the following command in the command prompt.

Node app

The following image shows the command execution


Step 7: Open the browser, IE, Chrome, and in the address-bar type the following address


The following result will be displayed


That’s it. Using a few lines of code and the http module, we just created a web server.


Node.js offers a simple way to create a web server which provides basic functionality for request processing. We can extend this to define routing, static pages responses, etc. using modules. We will explore this in the upcoming articles.

Download the entire source code of this article (Github)

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Mahesh Sabnis is a DotNetCurry author and a Microsoft MVP having over two decades of experience in IT education and development. He is a Microsoft Certified Trainer (MCT) since 2005 and has conducted various Corporate Training programs for .NET Technologies (all versions), and Front-end technologies like Angular and React. Follow him on twitter @maheshdotnet or connect with him on LinkedIn

Page copy protected against web site content infringement 	by Copyscape

Feedback - Leave us some adulation, criticism and everything in between!