Sending HTML Files
Bulk Delivery
Section titled “Bulk Delivery”If we want to send an entire file that already exists on disk as our response, instead of res.send() we use res.sendFile().
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 Catch
Section titled “The Catch”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).
Extra Bits & Bytes
Section titled “Extra Bits & Bytes”Express res.sendFile() - Demo Repo
Express API: res.sendFile