Using Express res.sendFile() Function to Serve Files

You can send files directly from the Express router using res.sendFile() method. You can send a file of any type such as HTML, PDF, Multimedia, etc.

res.sendFile() Method

Express provides a method in the response object of the router called sendFile() that can be used to serve static files.

res.sendFile() method accepts absolute paths only. You can use express.static() to set the path.

Example Code

Assuming you have Express installed in your project folder. Create a new folder called “public” and store a file in this folder.

Here is a example file called home.html and you can copy the content from the code shown below.

    <p>This is a test file!</p>

Here is the Express code to serve this file.

const express = require('express);
const router = express.Router();
const app = express();


/', (req,res) => {

/', router);

As you may notice, we are using express.static method to set the static path. Now all we need to do is pass the file name in the res.sendFile() method.

Try this code and let me know if you have any question!


Founder of Codeforgeek. Technologist. Published Author. Engineer. Content Creator. Teaching Everything I learn!

Articles: 298