Run a Node.js Server

Local Files versus Local Server

When you create an HTML file locally, like in the Frontend Dev Skill, and open it up in your browser, the browser will render all the elements it's able to and it will look like a webpage. It's reading the HTML, CSS and JS from a file it has access to. Your browsers address bar will look something like this, showing the location of the file on your computer:

local file

But as you know, most of the websites you want to visit aren't already on your computer, they're on the internet. Your browser has get the elements from servers that it needs to make the page. This back and forth of requests and responses is what goes on in between browsers and servers.

When you program servers, you're telling them what to do about the different kinds of requests they get.

With Node.js we can mimic that back and forth request/response relationship locally, using our omputer as a server. To do that, we'll write an HTTP server.

HTTP is HyperText Transfer Protocol and it's a way of moving HTML or HyperText Markup Language, files around with servers.

Our Simple Web Server Example

We've made a simple server that serves up an HTML page. It's on GitHub so all you need to do is clone it to your computer. In your Bash, navigate to where you want to copy the files to, for example, your Documents folder.

cd Documents
git clone

Run the Server

To run this Node.js module, we'll tell node to run app.js, which is the file with the server code.

node app.js

It should tell you that it's lisening on local port 3000. Now open a browser and visit localhost:3000 and you'll see the website! Your browser's address bar looks like this, with the port you're usig a local server with.

local server

Let's walk through what exactly is happening.


The diagram above illustrates how this whole thing works:

  • We create a server with instructions on how to handle a request
  • When the server gets a request it goes and fetches the file and it's information
  • It pipes out that information back as a response to the browser
  • The browser uses that information to build the website