How to serve static files in Node.js

Introduction

This time, I will explain how to route static files.

This section describes the routing method using the following versions.

nodejs v19.7.0

In addition, all the code created this time is posted on GitHub.

Static file routing

The minimal code to serve static files is below.

server.js

var http = require("http");
var fs = require("fs");
var path = require("path");

http
  .createServer(function (request, response) {
    var filePath = "." + request.url;
    if (filePath == "./") filePath = "./index.html";

    var extname = String(path.extname(filePath)).toLowerCase();
    var contentType = "text/html";
    var mimeTypes = {
      ".html": "text/html",
      ".js": "text/javascript",
      ".css": "text/css",
      ".json": "application/json",
      ".png": "image/png",
      ".jpg": "image/jpg",
      ".gif": "image/gif",
      ".wav": "audio/wav",
      ".mp4": "video/mp4",
      ".woff": "application/font-woff",
      ".ttf": "application/font-ttf",
      ".eot": "application/vnd.ms-fontobject",
      ".otf": "application/font-otf",
      ".svg": "application/image/svg+xml",
    };

    contentType = mimeTypes[extname] || "application/octet-stream";

    fs.readFile(filePath, function (error, content) {
      if (error) {
        if (error.code == "ENOENT") {
          fs. readFile("./404.html", function (error, content) {
            response.writeHead(200, { "Content-Type": contentType });
            response.end(content, "utf-8");
          });
        } else {
          response.writeHead(500);
          response.end(
            "Sorry, check with the site admin for error: " +
              error. code +
              " ..\n"
          );
          response.end();
        }
      } else {
        response.writeHead(200, { "Content-Type": contentType });
        response.end(content, "utf-8");
      }
    });
  })
  .listen(3000, () => console.log("listening on http://localhost:3000"));

Commentary

  • module import
var http = require('http');
var fs = require('fs');
var path = require('path');

The above code loads the http module for creating an HTTP server, the fs module for manipulating the file system, and the path module for manipulating file paths.

  • Create HTTP server
http.createServer(function (request, response) {
    // code omitted
}).listen(3000, () => console.log("listening on http://localhost:3000"));

This code starts an HTTP server on port 3000. If the server starts successfully, you should see the message ’listening on http://localhost:3000’ on the console. Inside the createServer function, we set up a callback function that will be called each time a request comes in.

  • File path parsing
var filePath = '.' + request.url;
if (filePath == './')
    filePath = './index.html';

Here we are generating the static file path from the request URL. If the request is for the root (’/’), it will return the default index file (index.html).

  • read files and generate responses
fs.readFile(filePath, function(error, content) {
    // code omitted
});

The above code reads the file from the parsed file path and returns the read content to the client as an HTTP response. If an error occurs (e.g. file not found), generate an appropriate error response.

As a result, you can directly access the URL http://localhost:3000/[file name] from a web browser, etc., and obtain the specified static file.

index.html

<h1>Hello World</h1>

test

Let’s run the above code and access http://localhost:3000/. It is successful if the following screen is displayed.

summary

In this article, we discussed how to serve static files with Node.js. In this article, we covered setting up an HTTP server and routing to static files. If you just want to serve static files such as HTML files, the above code should be enough. But real web applications need to serve dynamic content, not just static files.