Serving Static Assets Using http

Imagine you have a “treasure chest” of files inside your Node.js server—images, text documents, or any other unchanging resources. These treasures are static assets that can be sent to a client upon request. In Node.js, you can retrieve these treasures using the fs (file system) library and hand them over to the client through the http server.

In this tutorial, you’ll learn how to:

Finding and Reading Files

The fs library in Node.js is like a key to your file-based treasure chest. One of its most straightforward methods is readFileSync, which fetches a file from disk and returns its contents.

const fs = require('fs');

const fileContents = fs.readFileSync('./file-name.txt', 'utf-8');

Here, file-name.txt is the treasure you’re retrieving. The 'utf-8' argument ensures the data is returned as a readable string. Without this, you might get a Buffer (binary data) instead of text.

If you point to a file that doesn’t exist, readFileSync will throw an error, like trying to open a chest that isn’t there. For larger files, you could use readFile (asynchronous) to avoid blocking your code, but readFileSync is quick and easy to illustrate the concept.

Sending Files

Once you have your file’s content, all you need to do is serve it via your http server. Think of your server as a messenger handing off the “treasure” to whoever requests it.

const http = require('http');
const fs = require('fs');

const server = http.createServer((req, res) => {
  // Read the image (the static asset)
  const catImage = fs.readFileSync('./images/cat.png');

  // Set the status code to 200, meaning "OK"
  res.statusCode = 200;
  
  // Because we're sending a PNG image, set the Content-Type accordingly
  res.setHeader('Content-Type', 'image/png');
  
  // Send the image data as the response body
  res.end(catImage);
});

server.listen(3000, () => {
  console.log('Server listening on port 3000');
});

Here’s what’s happening:

Setting the right Content-Type header is crucial. It’s how the client knows to display the response as an image, a CSS stylesheet, or other