Fixing Node.js ENOENT Error: File or Directory Not Found
The ENOENT
error in Node.js indicates that the file or directory you are trying to access does not exist.
This is a common error that occurs when using the fs
module to read, write, or modify files.
For instance, attempting to read a file using fs.readFileSync('missing-file.txt')
will throw the error ENOENT: no such file or directory
.
The error happens due to incorrect file paths, typos, or deleted/moved files.
To fix this, ensure the file exists at the specified path.
Use fs.access
to check file existence before accessing it, like this: fs.access(filePath, fs.constants.F_OK, (err) => { if (err) { console.error('File not found'); } });
.
Also, always use path
for path resolution.