Path Modules in Express JS - res.sendFile()

In Express.js, the res.sendFile() method is used to send a file to the client. This method is part of the response object, and it is useful when you need to serve static files such as HTML, images, or other types of files.

Syntax :: 
res.sendFile(path, [options], [callback])

Parameters:

  1. path: The absolute path of the file you want to send.
  2. options (optional):
    An object to configure headers and other settings for the response.
  3. callback (optional):
    A function that gets invoked after the file is sent or if an error occurs.

Example 1: Basic Usage

Here’s how you can use res.sendFile() to send a file:

const express = require('express');
const path = require('path');
const app = express();

app.get('/', (req, res) => {
  const filePath = path.join(__dirname, 'index.html');
  res.sendFile(filePath);
});

app.listen(3000, () => {
  console.log('Server is running on http://localhost:3000');
});

  • path.join(__dirname, 'index.html') generates the absolute path for the file.
  • Make sure the file exists at the given location.
  • 1- setup package > npm init -y
  • 2- install express > npm i express
  • 3- in that root folder> create 'index.html' page


  • Key Methods in the Path Module

    MethodDescription
    path.join()Joins multiple path segments into one.
    path.resolve()Resolves a sequence of paths into an absolute path.
    path.dirname()Returns the directory name of a path.
    path.basename()Returns the last portion of a path.
    path.extname()Returns the extension of the path.
    path.normalize()Normalizes a given path (removes redundant segments).
    path.isAbsolute()Determines if the given path is an absolute path.
    path.parse()Returns an object with details like root, dir, base, ext, and name.
    path.format()Returns a path string from an object created by path.parse().

    By combining the path module with Express.js, you can build applications that handle file paths and directories in a clean and robust manner.