Categories
Express JavaScript Answers

How to Serve Static Files with Express.js?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *