EN
Node.js - file exists
0
points
In this article, we would like to show you how to check that file is exists using Node.js.
Practical examples
Synchronous version:
const fs = require('fs');
const path = './path/to/file.txt';
try {
if (fs.existsSync(path)) {
console.log('File exists!');
} else {
console.log('File does not exist!');
}
} catch (error) {
console.error(error);
}
Asynchronous version:
const fs = require('fs/promises');
const fileExists = async (path) => {
try {
await fs.access(path);
console.log('File exists!');
} catch (error) {
console.error(error.message);
}
};
fileExists('./path/to/file.txt');