To serve static files with Express.js, we can use the express.static
middleware.
For instance, we can write:
const express = require('express')
const app = express()
const port = 3000
app.use(express.static(__dirname + '/public'));
app.get('/', (req, res) => {
res.send('hello world')
})
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
We call app.use
with express.static(__dirname + ‘/public’)
to serve the public
folder in the project folder as the static folder.
This will expose the folder’s contents to the public.
Therefore, if we have a foo.txt
file in the public
folder, we can go to /foo.txt
to see its contents.