🎓 A1Learner
🔍
0 of 50 lessons completed

Serving Static Files

A static file is a file sent to the browser as it is. Express can serve a whole folder of static files.

Serve the public folder

This line serves the public folder.

app.use(express.static("public"));

Ask for the file

This command asks the server for the file.

curl http://localhost:3000/hello.txt

Example

const express = require("express");

const app = express();

app.use(express.static("public"));

app.listen(3000, () => {
  console.log("Notes API running on http://localhost:3000");
});

Key points

  • A static file is a file sent to the browser as it is.
  • A text file is one example of a static file.
  • Use express.static with a folder name to serve the folder.
  • Put the files for the site in a folder named public.
  • Make a file named hello.txt inside the public folder, with the words Hello from a static file! inside it.
  • An ask for /hello.txt then sends the file hello.txt.

In this example, the app.use line serves the public folder. The file hello.txt sits inside that folder. The listen line starts the server on port 3000. A visit to /hello.txt shows the words from the file.

Note

Static files need no route of their own.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Which line serves the public folder?