Create a web server (Node.js) to serve simple html


What is Node.js?

  • Node.js is an open source web server environment
  • It can run JavaScript outside the browser.

In this post, let’s write a web server using Node.js to serve simple HTML files.

Requirement: Install Node.js

LTS version is recommended.

Approach 1: creating server using a built-in ‘http’ module

Step 1: Create index.html to be served

Step 2: write server code using http module

Step 3: run the server

$ node server.js

Then your index.html page will be available on URL: http://localhost:8080

Our Node server can server different html content based on different HTTP requests. So we can write our server like this:

And here are results:

Not handled http request

Approach 2: using an existing server (http-server)

Step 1: Install http-server

$ sudo npm install http-server$ cd node_modules/

$ cd http-server

Step 2: Create a HTML file inside directory:node_modules/http-server/bin

$ cd bin
$ vim index.html

Step 3: Run the server

$ node http-server . /* run server in current directory*/

You can access HTML file through the above three addresses. Eg:

Also, your machine name as hostname. In my case:

$ hostname


In addition to html file, Node web server can also serve JavaScript code.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store