TypeError: path must be absolute or specify root to res.sendFile
- Published
- Reading time
- 1 min read
- Length
- 264 words
On this page
TypeError: path must be absolute or specify root to res.sendFile#
If you have encountered this error while working with Node.js, it means that the 'path' argument that you have passed to res.sendFile() method is not a valid absolute path.
This error is usually caused when you are trying to send a file using res.sendFile() method, but the path that you have provided is not correct or incomplete.
What is an Absolute Path?#
An absolute path is a complete path that starts from the root directory of the file system. It includes all the directories and subdirectories that are required to locate a file or directory.
For example, if you are working on a Linux system, an absolute path will start with a forward slash (/), followed by the directories and subdirectories.
res.sendFile('/home/user/Documents/index.html');In the above code, '/home/user/Documents/index.html' is an absolute path.
How to Fix the Error?#
To fix this error, you need to provide a valid absolute path to the res.sendFile() method. You can do this in two ways:
- Use the __dirname Variable: __dirname is a global variable that represents the directory name of the current module. You can use this variable to create an absolute path to a file.
res.sendFile(__dirname + '/index.html');- Use the Path Module: Node.js provides a built-in module called 'path' that can be used to manipulate file paths. You can use this module to create an absolute path to a file.
const path = require('path');
res.sendFile(path.join(__dirname, 'public', 'index.html'));