Skip to content

Sending HTML Files

If we want to send an entire file that already exists on disk as our response, instead of res.send() we use res.sendFile().

Shipyard crane lifting a shipping container labeled index.html onto a truck.

Fig 1: Bulk Freight. Moving the entire container.

For example, supposing we have a pages directory and within that we have index.html.

app.get('/', (req, res) => {
// Wait... we need an absolute path
res.sendFile('/absolute/path/to/pages/index.html');
});

The path that we pass to sendFile() must be absolute. You can’t just say ./pages/index.html.

Why? Because Node needs to find the file on the Server’s Hard Drive. It doesn’t know where the “truck” (the running process) is parked relative to where the file is stored.

To find our current GPS coordinates on the server’s file system, we use __dirname. (More on how to calculate this safely in the next lesson).


Express res.sendFile() - Demo Repo

Express API: res.sendFile

⏭ Following the Path

We need a safer way to calculate file paths than just adding strings together.