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.

<html>
<head>
    <title>Home</title>
</head>
<body>
    <p>This is a test file!</p>
</body>
</html>

Here is the Express code to serve this file.

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

app.use(express.static('
public'));

router.get('
/', (req,res) => {
    res.sendFile('
home.html');
});

app.use('
/', router);
app.listen(3000);

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!