Front-end Tutorials

Front-end Tutorials

HTMLCSSSassJavaScriptReactJS
CMS Tutorials

CMS Tutorials

WordPress
Tutorials expand

Express res.sendFile() Method

Updated on Nov 24, 2024
By Mari Selvan
👁️ 226 - Views
⏳ 4 mins
💬 1 Comment
Express res.sendFile() Method

Photo Credit to CodeToFun

🙋 Introduction

In web development, serving files is a common task, whether it's static assets, images, or entire HTML documents.

Express.js simplifies this process with the res.sendFile() method, designed to effortlessly send files as responses.

In this guide, we'll explore the syntax, use cases, and best practices of the res.sendFile() method in Express.js.

💡 Syntax

The syntax for the res.sendFile() method is straightforward:

syntax.js
Copied
Copy To Clipboard
res.sendFile(path [, options] [, callback])
  • path: A string representing the file path or a complete file path.
  • options (optional): An object with additional options for sending the file.
  • callback (optional): A callback function that will be executed once the file is sent.

❓ How res.sendFile() Works

The res.sendFile() method is used to send a file as an HTTP response to a client. It automatically sets the appropriate Content-Type header based on the file extension and provides options for additional configurations.

example.js
Copied
Copy To Clipboard
const express = require('express');
const app = express();

app.get('/download/:file', (req, res) => {
  const fileName = req.params.file;
  const filePath = `./downloads/${fileName}`;
  
  res.sendFile(filePath, { root: __dirname });
});

const PORT = 3000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

In this example, a route is created to handle requests for downloading files. The res.sendFile() method is used to send the requested file from the 'downloads' directory.

📚 Use Cases

  1. Serving Static Files:

    Use res.sendFile() to serve static files like HTML, CSS, and JavaScript from a specified directory.

    example.js
    Copied
    Copy To Clipboard
    app.use(express.static('public'));
    
    app.get('/home', (req, res) => {
      res.sendFile('index.html', { root: __dirname + '/public' });
    });
  2. File Download Routes:

    Create routes dedicated to file downloads, using res.sendFile() to send files in response to client requests.

    example.js
    Copied
    Copy To Clipboard
    app.get('/download/:file', (req, res) => {
      const fileName = req.params.file;
      const filePath = `./downloads/${fileName}`;
      
      res.sendFile(filePath, { root: __dirname });
    });

🏆 Best Practices

  1. Security Considerations:

    Ensure that file paths are properly sanitized and validated to prevent directory traversal attacks.

    example.js
    Copied
    Copy To Clipboard
    app.get('/download/:file', (req, res) => {
      const fileName = req.params.file;
      
      // Validate file name to prevent directory traversal
      if (!isValidFileName(fileName)) {
        res.status(400).send('Invalid file name');
        return;
      }
      
      const filePath = `./downloads/${fileName}`;
      res.sendFile(filePath, { root: __dirname });
    });
  2. Setting Custom Headers:

    Use the options parameter to set custom headers if needed, such as Content-Disposition for controlling file download behavior.

    example.js
    Copied
    Copy To Clipboard
    app.get('/download/:file', (req, res) => {
      const fileName = req.params.file;
      const filePath = `./downloads/${fileName}`;
      
      const options = {
        headers: {
          'Content-Disposition': `attachment; filename=${fileName}`
        }
      };
      
      res.sendFile(filePath, options);
    });

🎉 Conclusion

The res.sendFile() method in Express.js simplifies the process of serving files, making it an essential tool for handling various file-related scenarios. Whether you're serving static assets or providing file downloads, understanding how to use res.sendFile() will enhance your Express.js applications.

Now, equipped with knowledge about the res.sendFile() method, go ahead and streamline your file-serving tasks in Express.js!

👨‍💻 Join our Community:

To get interesting news and instant updates on Front-End, Back-End, CMS and other Frameworks. Please Join the Telegram Channel:

Author

author
👋 Hey, I'm Mari Selvan

For over eight years, I worked as a full-stack web developer. Now, I have chosen my profession as a full-time blogger at codetofun.com.

Buy me a coffee to make codetofun.com free for everyone.

Buy me a Coffee

Share Your Findings to All

Subscribe
Notify of
guest
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Mari Selvan
Mari Selvan
9 months ago

If you have any doubts regarding this article (Express res.sendFile() Method), please comment here. I will help you immediately.

We make use of cookies to improve our user experience. By using this website, you agree with our Cookies Policy
AgreeCookie Policy