In this article, we’ll look at how to serve static files in Express.
To serve static files such as HTML, CSS, JavaScript, and images, we can use Express’s built-in express.static
middleware function.
express.static(root, [options])
app.use(express.static(‘public’))
In this example, we’ll serve
Following this installation structure, we can create our Node project as bellow:
mkdir my-project
cd my-project
npm init -y
We then create index.js to store our Express server:
touch index.js
Install Express as a dependency:
npm install express --save
This example has an index.html file, style.css, and an image.
To store these files on the client side, we create a public directory and include them. Our public folder looks like this:
my-project
|- index.js
|- public
|- hello.png
|- index.html
|- style.css
In this step, we require Express and write a simple Hello world.
const express = require("express");
const app = express();
const PORT = 3000;
app.get("/", (req, res) => {
res.send("Hello World");
});
app.listen(PORT, () => console.log(`Server listening on port: ${PORT}`));
We’ll want to point to the folder serving our static files.
app.use(express.static(path.join(__dirname, "public")));
Putting it together
const express = require("express");
const app = express();
const PORT = 3000;
app.use(express.static(path.join(__dirname, "public")));
app.listen(PORT, () => console.log(`Server listening on port: ${PORT}`));
Now we can add any file we want in the public directory, such as about.html, and we go to “/about.html” and will see the server running.