Express JavaScript Answers

How to Serve a Single Static File with Express.js?

Spread the love

To serve a single static file 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("/foo.txt", express.static(__dirname + '/foo.txt'));

app.get('/', (req, res) => {
  res.send('hello world')

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)

to add:

app.use("/foo.txt", express.static(__dirname + '/foo.txt'));

to use the express.static middleware to expose the foo.txt file to the public.

We make it accessible by making a request to “/foo.txt” since that’s the first argument we passed into app.use .

And we make it serve the foo.txt file from the current working directory with:

express.static(__dirname + '/foo.txt')

So when we make a request to /foo.txt , we would see its contents in the response.

By John Au-Yeung

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

Leave a Reply

Your email address will not be published.