Simple HTTP Server in NodeJS: Part 1

Introduction

In previous articles we dealt with the file system read/write operations in synchronous and asynchronous modes. Basically, these are something local that we deal with on local computers. And now we will try to implement something that is really a particle in nature and quite often used by node.js.

So, today we will start with a HTTP server. And for that we will explore the http module of node.

Background

In every node tutorial, we use some module implicitly and they are the backbone of node. So, first we will explore that module that we will use in this demonstration. And, it is http.

Note: Node.js v0.12.0 Manual & Documentation.

Let's check out the node API documentation.

http

As a HTTP server we are trying to write a server-side script that accepts a HTML page name as input and sends the HTML code to the client-browser if the requested page is valid else it will return NOT FOUND(404).

Code

Code

This is one of the simplest HTTP servers created on node that returns “Hello World” on every request.

Before we roceed further I want to point out some important methods that we used in this code snippet.

  • http.serverCreate()
  • response.headWrite()
  • response.write()
  • http.end
  • http.listen()

serverCreate() is one argument method where you assign a callback function that is called when the server is initiated.

Where headWrite() is a method with two arguments. And it is just used to a header to the client system/browser.

The same with the write() and end() methods that data to the client system as responses.

Finally, we have the listen() method that lists all the time with the given socket address (host: port).

Moving to the code

In the beginning we included the http module in our code and then assigned a host and port value that are pre-requites for any server. Then we will set up the server along with the callback function, where we set the header and response data.

At the end, we set the listing () method that accepts a callback function.

And, when we execute this then we have something like this:

execute

And now, it is listing to socket address 127.0.0.1:1337. We will now request to this server address via our browser.

So, let's do it:

output

Yes, we got our desired value, Hello World. And, in CMD we have something like this:

Hello World

Here, Received Request: / (Null) because we haven't added anything. If we request something like this: http://127.0.0.1:1337/hello.html.

Then, I will have a Received Request: /hello.html.

Request

Conclusion

So, this is one of the fundamental ways to create a HTTP server. Next, we try our hands on an intelligent server that processes requests and sends HTML pages depending on that.


Similar Articles