Express.js res.sendFile() Function
Last Updated :
03 May, 2025
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.
Similar Reads
Express res.send() Function
The res.send function is used to send a response in form of various types of data, such as strings, objects, arrays, or buffers, and automatically sets the appropriate Content-Type header based on the data type. res.send in ExpressThe res.send() function sends the HTTP response. The body parameter c
3 min read
Express.js res.set() Function
The res.set() function is used to set the response HTTP header field to value. To set multiple fields at once, pass an object as the parameter. Syntax: res.set(field [, value])Parameters: The field parameter is the name of the field and the value parameter is the value assigned to the field paramete
2 min read
Express.js res.sendStatus() Function
The res.sendStatus() function is used to set the response HTTP status code to statusCode and send its string representation as the response body. Syntax: res.sendStatus( statusCode )Parameter: The statusCode parameter describes the HTTP status code. Returns: It returns an Object. Installation of the
2 min read
Express.js res.type() Function
The res.type() function is used to set the Content-Type HTTP header to the MIME type determined by the mime.lookup() function for the specified type. Syntax: res.type( type ) Parameters: The type parameter describes the MIME type. Return Value: It returns an Object. Installation of the express modul
2 min read
Express res.json() Function
The res.json() function sends a JSON response. This method sends a response (with the correct content-type) that is the parameter converted to a JSON string using the JSON.stringify() method. Syntax: res.json( [body] )Parameters: The body parameter is the body that is to be sent in the response. Ret
2 min read
Express.js | app.render() Function
The app.render() function is used to render the HTML of a view via the callback function. This function returns the HTML in the callback function. Syntax: app.render(view, [locals], callback)Parameters: view: It is the name of the HTML page which is to be rendered.locals: It is an optional parameter
2 min read
Express.js | router.use() Function
The router.use() function uses the specified middleware function or functions. It basically mounts middleware for the routes which are being served by the specific router. Syntax: router.use( path, function )Parameters: Path: It is the path to this middleware, if we can have /user, now this middlewa
2 min read
Express.js res.vary() Function
The res.vary() function is used to add the field to the Vary response header, if it is not there already. The Vary header indicates which headers itâs basically used for content negotiation. Syntax: res.vary( field ) Parameter: The field parameter describes the name of the field. Return Value: It re
2 min read
Express.js req.range() Function
The req.range() function is basically a Range header parser where the Accept-Ranges response-header field allows the server to indicate its acceptance of range requests for a resource. Syntax: req.range(size[, options]) Parameter: size: It is the maximum size of the resource.options: It is an object
2 min read
Express.js res.get() Function
The res.get() function returns the HTTP response header specified by the field. The match is case-insensitive. Syntax: res.get( field ) Parameter: The field parameter describes the name of the field. Return Value: It returns an Object. Installation of the express module: You can visit the link to In
2 min read