June 18, 2024

Express res.sendFile() Method With Examples

In an ExpressJS application if you want to transfer the file at the given path then that can be done using response.sendFile() method. There is a similar method res.download() in Express.js which sends a file for download, difference between these two methods is that with res.sendFile() file is displayed by the browser whereas with res.download() browser prompts to download the sent file.

res.sendFile() method in Express.js

This method transfers the file at the given path and sets the Content-Type response HTTP header field based on the filename's extension.

res.sendFile() syntax

res.sendFile(path, options, fn)
  • path- absolute path to the file. It can be just the filename if root option is set in the options object.
  • options- This is an optional parameter to set properties like root, headers and many more. See the list of available options here- https://expressjs.com/en/4x/api.html#res.sendFile
  • fn- A callback function which is invoked when the transfer is complete or when an error occurs. Takes one parameter err which encapsulates the error.

res.sendFile example in Express.js

1. Sending an HTML file

If you want to send file views/person.html with in project root directory and the code is in examples/sendfile.js

views/person.html

<!DOCTYPE html>
<html>
<head>
    <title>Person Form</title>
</head>
<body>
    <form action="/savePerson" method="post">
        <label for="name">Enter Name</label>
        <input type="text" name="name">
        <br/>
        <label for="email">Enter email</label>
        <input type="text" name="email">
        <br/>
        <button type="submit">Submit</button>
    </form>
</body>

examples/sendfile.js

const express = require('express');
const app = express();
const path = require('path');
const port = 3000;
app.get('/', (req, res) => {
    const options = {
        root: path.join(__dirname, '..', 'views'),
        headers: {
          'x-timestamp': Date.now()
        }
    }
    const fileName = 'person.html';
    res.sendFile(fileName, options, (err)=>{
        if(err){
            console.error('Error while sending file:', err);
        }else{
            console.log('file ' + fileName + ' sent successfully');
        }
    })
})

app.listen(port, () => {
    console.log(`Example app listening on port ${port}`)
});

As you can see, as the first parameter to sendFile() only the file name is passed. That is done because root property is set in options object.

root: path.join(__dirname, '..', 'views')

What it is doing is to go one level up from the current directory and then go to views directory.

On running the file and accessing the URL- http://localhost:3000 you should see the person.html file displayed.

2. Sending an image

Same way if you want to send an image named testimage.png residing in /public/images directory.

const express = require('express');

const app = express();

const path = require('path');

const port = 3000;

app.get('/', (req, res) => {
    const options = {
        root: path.join(__dirname, '..', 'public', 'images'),
        headers: {
          'x-timestamp': Date.now()
        }
    }
    const fileName = 'testimage.png';
    res.sendFile(fileName, options, (err)=>{
        if(err){
            console.error('Error while sending file:', err);
        }else{
            console.log('file ' + fileName + ' sent successfully');
        }
    })
})


app.listen(port, () => {
    console.log(`Example app listening on port ${port}`)
});

On running the file and accessing the URL- http://localhost:3000 you should see the image displayed.

That's all for the topic Express res.sendFile() Method With Examples. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment