Create a Web Server using Node.js

Posted by: Mahesh Sabnis , on 10/21/2015, in Category Node.js
Views: 16430
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.

vscode-new-file

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.

//1.
var http = require('http');
//2.
var server = http.createServer(function (req, resp) {
    //3.
    resp.writeHead(200, { 'Content-Type': 'text/html' });
    //4.
    resp.end("Hello, this is the test web server created");
});
//5.
server.listen(5050);
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.

vscode-command-prompt

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

Node app

The following image shows the command execution

nodejs-command-execution

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

http://localhost:5050

The following result will be displayed

webserver

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

Conclusion

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)

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

Author
Mahesh Sabnis is a DotNetCurry author and Microsoft MVP having over 17 years 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). Follow him on twitter @maheshdotnet


Page copy protected against web site content infringement 	by Copyscape




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

Categories

JOIN OUR COMMUNITY

POPULAR ARTICLES

FREE .NET MAGAZINES

Free DNC .NET Magazine

Tags

JQUERY COOKBOOK

jQuery CookBook