O'Reilly logo

Node for Front-End Developers by Garann Means

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Serving a Static Page

Realistically, we won’t want to manually write out the contents of each page we want to serve from within our JavaScript. It’s much more maintainable to store our HTML as HTML in separate files.

Since our pure HTML page will contain no logic, we can move it to the front-end of our application and create it in our public folder (or whatever the equivalent is in your directory structure). In this example we’ll adhere to predictable conventions from other servers and call our main page index.html, but feel free to name yours whatever makes sense. Since we’re writing our own server, there’s no defined list of filenames it will try to locate to get the default content for the current directory, so if you use those conventions, the only advantage is predictability. Let’s start by creating that page and moving the same HTML we were writing in JavaScript into it:

<!doctype html>
<html>
  <head>
    <title>Hello world</title>
  </head>
  <body>
    <h1>Hello, world!</h1>
  </body>
</html>

To ensure that our HTML page gets served correctly, we’ll need to change our server code to investigate the request being made of it. Instead of providing the same response for anything the user requests, we should check whether the requested file’s extension is .html, make sure the resource actually exists, and if it does, load and return the body of the corresponding file. To do that, we’ll need to rewrite the body of our createServer() callback:

var http = require("http"), // utilities for working ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required