Open In App

Express.js res.sendFile() Function

Improve
Improve
Like Article
Like
Save
Share
Report

The res.sendFile() function 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: The path parameter describes the path and the options parameter contains various properties like maxAge, root, etc and fn is the callback function.

Returns: It returns an Object.

Steps to Install the express module:

Step 1: Run the following commands to initialize the project and create an index file & env file. (Make sure you have node and npm installed)

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": "^4.18.2",
}

Example: Below is the example of the expressjs res.sendFile() Function

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);
});


Now, create a .txt file like here we have created Hello.txt in the root directory of the project with the following text:  

Greetings from GeeksforGeeks

Steps to run the program: 

node index.js

Output: 

Server listening on PORT 3000

Console 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

Last Updated : 05 Jan, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads