Open In App

Express.js res.sendFile() Function

Last Updated : 03 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The res.sendFile() function in Express.js is a convenient method for sending static files (like HTML, PDFs, images, or other media) directly to the client. It transfers the file at the given path and it sets the Content-Type response HTTP header field based on the filename extension. 

Syntax

res.sendFile(path [, options] [, fn])

Parameter

  • path: The absolute or relative path to the file you want to send.
  • options: (Optional) An object where you can configure settings such as headers or caching.
  • fn: (Optional) A callback function that handles errors, typically invoked with an error object if the file cannot be sent.

Returns: It returns an Object.

Steps to Implement res.sendFile() Function

Step 1: Run the following commands to initialise the project.

npm init -y

Step 2: Installing required packages

npm install express

Folder Structure

Project Structure

The updated dependencies in package.json file will look like:

"dependencies": {
    "express": "^5.1.0",
}

Step 3: Create a index.js, .env and a text file and implement the res.sendFile() function using the code provided.

JavaScript
const express = require('express');
const app = express();
const path = require('path');
const PORT = 3000;

// Without middleware
app.get('/', function (req, res) {
    const options = {
        root: path.join(__dirname)
    };

    const fileName = 'Hello.txt';
    res.sendFile(fileName, options, function (err) {
        if (err) {
            console.error('Error sending file:', err);
        } else {
            console.log('Sent:', fileName);
        }
    });
});

app.listen(PORT, function (err) {
    if (err) console.error(err);
    console.log("Server listening on PORT", PORT);
});

In the Hello.txt file add the following text

Greetings from GeeksforGeeks

Run the application using the following command

node index.js

Output: Now open the browser and go to http://localhost:3000/, now check your console and you will see the following output: 

Server listening on PORT 3000
Sent: Hello.txt

Use Cases for res.sendFile()

  • Serving Static Files: res.sendFile() is ideal for serving static files such as HTML, CSS, JavaScript, and media files like images or videos directly from your server to the client.
  • File Downloads: You can use this method to allow users to download files. For example, serving PDF reports, downloadable documentation, or software packages.
  • Serving Templates: If you are serving HTML templates (e.g., EJS files) directly to the client, you can use res.sendFile() for static content like static HTML pages or as a fallback when templates are not rendered dynamically.

Error Handling in res.sendFile():

Handling errors properly is crucial to ensure the client receives a proper response when something goes wrong (e.g., if the file doesn’t exist or can’t be accessed). Express allows you to pass a callback function to handle errors.

JavaScript
res.sendFile(filePath, (err) => {
   if (err) {
       console.log('Error sending file:', err);
       res.status(500).send('File not found');
   } else {
       console.log('Sent:', 'Hello.txt');
   }
});

In this example

  • If the file is successfully sent, you’ll see a log message indicating that the file was sent.
  • If there’s an error (like the file not being found), the err callback will trigger. We log the error and send a 500 status with a message like “File not found”.

Conclusion

The res.sendFile() function in Express is a simple and efficient way to serve static files like HTML, PDFs, images, and more directly from your server to the client. By providing the correct file path, optional settings, and an error handling callback, you can easily manage file serving in your web applications.



Next Article

Similar Reads