NodeJS: Check if file exists and is readable (fs.exists() replacement)
This is the best function for checking if a file exists and is readable in Node.js. It’s a replacement for the deprecated fs.exists()
function.
Pure Javascript:
const fs = require('fs').promises;
async function fileExistsAndIsReadable(path) {
try {
await fs.access(path, fs.constants.F_OK | fs.constants.R_OK);
return true;
} catch (err) {
return false;
}
}
or using TypeScript:
import { access, constants } from 'fs/promises';
import { PathLike } from 'fs';
export async function fileExistsAndIsReadable(path: PathLike): Promise<boolean> {
try {
await access(path, constants.F_OK | constants.R_OK);
return true;
} catch (err) {
return false;
}
}
Usage example:
// Usage example:
const path = 'path/to/your/file.txt';
fileExistsAndIsReadable(path)
.then((result) => {
if (result) {
console.log('File exists and is readable');
} else {
console.log('File does not exist or is not readable');
}
})
.catch((err) => {
console.error('An unexpected error occurred', err);
});