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
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
<!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
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
var http = require("http"), // utilities for working ...