🤯 50% Off! 700+ courses, assessments, and books

Creating a HTTP Server in Node.js

Colin Ihrig
Share

In my last article, I introduced the most basic Node.js program possible. While Hello World programs are nice, Node.js is more commonly known for creating highly scalable server applications. This article introduces a simple HTTP server built atop Node.js.

Running the Server

Start by creating a new file named “web_server.js”. Insert the following code into the file and save it.

var http = require("http");
var server = http.createServer(function(request, response) {
  response.writeHead(200, {"Content-Type": "text/html"});
  response.write("<!DOCTYPE "html">");
  response.write("<html>");
  response.write("<head>");
  response.write("<title>Hello World Page</title>");
  response.write("</head>");
  response.write("<body>");
  response.write("Hello World!");
  response.write("</body>");
  response.write("</html>");
  response.end();
});

server.listen(80);
console.log("Server is listening");

To start the server, type the command shown below. If everything works properly, you will see a message that the server is listening. Note that the example server attempts to bind to port 80, the standard HTTP port. If this port is already in use, or is restricted on your machine, you will experience an error.

node web_server.js

The next step is to connect to the server using a web browser. Launch your browser of choice, and direct it to either of the following links. In networking terms, localhost (and it’s IP address of 127.0.0.1) refers to the machine you are currently using. Your browser should be saying “Hello World!”.

http://localhost
http://127.0.0.1

How the Server Works

Now that the server is up and running, it’s time to analyze the code. The first thing to notice is the call to require() on line 1. Node.js provides a simple module system with a large developer community. Node.js programs can load individual modules using the require() method. While many modules must be downloaded, some modules, such as http are included with Node.js installations.

On line 2, the HTTP server is created using the http module’s createServer() method. Like most Node.js functions, createServer() takes a callback function as an argument. This callback function is executed each time the server receives a new request.

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

The callback function begins by calling the response.writeHead() method. This method sends an HTTP status code and a collection of response headers back to the client. The status code is used to indicate the result of the request. For example, everyone has encountered a 404 error before, indicating that a page could not be found. The example server returns the code 200, which indicates success.

Along with the status code, the server returns a number of HTTP headers which define the parameters of the response. If you do not specify headers, Node.js will implicitly send them for you. The example server specifies only the Content-Type header. This particular header defines the MIME type of the response. In the case of an HTML response, the MIME type is “text/html”.

Next, the server executes several calls to response.write(). These calls are used to write the HTML page. By default, UTF-8 character encoding is used. Technically, all of these calls could be combined into a single call to improve performance. However, for such a trivial example, performance has been sacrificed for the sake of code readability.

After the HTML page has been written, the response.end() method is called. By calling this method, we are telling the server that the response headers and body have been sent, and that the request has been fulfilled. The example server calls end() with no parameters. However, end() can also be called like write(), assuming only one call is needed.

The call to listen() on line 15 causes the server to bind to a port and listen for incoming connections. Computers have thousands of ports, which act as communication end points. In order to connect to the server, clients must know exactly which port the server is listening on. Ports are identified by port numbers, with HTTP servers typically listening to port 80.

Conclusion

This article has presented a very basic HTTP server. In its current state, the server can only return a single HTML page. In the coming weeks, we will dive deeper into the world of Node.js, exploring additional features such as reading web pages from the file system and incorporating HTTP authentication.

If you’ve enjoyed this post, you’re going to want to learn all about SitePoint’s newest series of print and ebooks, Jump Start. The first title is Node.js by Don Nguyen — find out more at SitePoint!