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:
- path: The absolute path of the file you want to send.
- options (optional):
An object to configure headers and other settings for the response. - 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:
path.join(__dirname, 'index.html')
generates the absolute path for the file.Key Methods in the Path Module
Method | Description |
---|---|
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.