Creating a HTTP Server in Node.js

Share this article

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!

Frequently Asked Questions (FAQs) about Creating a HTTP Server in Node.js

What is the purpose of the ‘http.createServer()’ method in Node.js?

The ‘http.createServer()’ method is a built-in function in Node.js that is used to create a new instance of an HTTP server. This server listens for incoming requests and sends responses. It takes a requestListener function as an argument, which is automatically added to the ‘request’ event. This function is called each time the server gets a request. The requestListener function has two parameters: request (an instance of http.IncomingMessage) and response (an instance of http.ServerResponse).

How does the ‘response.writeHead()’ method work in Node.js?

The ‘response.writeHead()’ method is a function in Node.js that sends a response header to the request. The method takes two arguments: the status code and a plain object that represents the response headers. The status code is a 3-digit HTTP status code, and the second argument is an object where each key-value pair represents a header name and its value. This method must be called before ‘response.end()’ and can only be called once per response.

What is the difference between ‘write’ and ‘writeHead’ in Node.js?

The ‘write’ and ‘writeHead’ methods in Node.js are both used in the process of sending a server response. The ‘writeHead’ method is used to send an HTTP status code and a collection of response headers, while the ‘write’ method is used to send a response body to the client. The ‘writeHead’ method should be called before ‘write’, and both should be called before ‘end’, which signals the server that all of the response headers and body have been sent.

How can I use the ‘node-http-server’ package in Node.js?

The ‘node-http-server’ is a simple, configurable HTTP or HTTPS server for Node.js. To use it, you first need to install it using npm (Node Package Manager) by running ‘npm install node-http-server’. After installation, you can require it in your Node.js file and use its ‘deploy’ method to start the server. The ‘deploy’ method takes a configuration object as an argument, where you can specify server options like port, root, and serverIndex.

How can I handle HTTP requests and responses in Node.js?

In Node.js, you can handle HTTP requests and responses using the ‘http’ module. First, you need to create an HTTP server using the ‘http.createServer()’ method. This method takes a callback function as an argument, which is executed each time the server gets a request. The callback function has two parameters: ‘request’ and ‘response’. The ‘request’ object can be used to get information about the client request, like the URL, HTTP headers, and payload. The ‘response’ object is used to send a response back to the client. You can set the HTTP status code and headers using the ‘response.writeHead()’ method, write a response body using the ‘response.write()’ method, and end the response using the ‘response.end()’ method.

Colin IhrigColin Ihrig
View Author

Colin Ihrig is a software engineer working primarily with Node.js. Colin is the author of Pro Node.js for Developers, and co-author of Full Stack JavaScript Development with MEAN. Colin is a member of the Node.js Technical Steering Committee, and a hapi core team member. Colin received his Bachelor of Science in Engineering, and Master of Science in Computer Engineering from the University of Pittsburgh in 2005 and 2008, respectively.

IntermediateLearn-Node-JSnode.jsserver-side
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week