Send Static Files in Express with sendFile()

Mar 13, 2020

Express' sendFile() function lets you send a raw file as a response to an HTTP request. You can think of res.sendFile() as Express' static middleware for a single endpoint.

Using sendFile()

Suppose you have an HTML file test.html that looks like this:

<h1>Hello, World</h1>

You can make Express serve this HTML file as an HTTP response using res.sendFile() by passing the path to test.html. Note that the path must be absolute unless you specify the root option.

app.get('/myendpoint', (req, res) => {
  res.sendFile(`${__dirname}/test.html`);
});

If you don't want to specify the absolute path, you can pass the root option to specify the directory the path is relative to.

app.get('/myendpoint', (req, res) => {
  res.sendFile('test.html', { root: __dirname });
});

Want to become your team's Express expert? There's no better way to really grok a framework than to write your own clone from scratch. In 15 concise pages, this tutorial walks you through how to write a simplified clone of Express called Espresso. Get your copy!

Espresso supports:
  • Route handlers, like `app.get()` and `app.post()`
  • Express-compatible middleware, like `app.use(require('cors')())`
  • Express 4.0 style subrouters
As a bonus, Espresso also supports async functions, unlike Express.

Get the tutorial and master Express today!

Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Express Tutorials