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.
Synchronous version:
xxxxxxxxxx
1
const fs = require('fs');
2
3
const path = './path/to/file.txt';
4
5
try {
6
if (fs.existsSync(path)) {
7
console.log('File exists!');
8
} else {
9
console.log('File does not exist!');
10
}
11
} catch (error) {
12
console.error(error);
13
}
Asynchronous version:
xxxxxxxxxx
1
const fs = require('fs/promises');
2
3
const fileExists = async (path) => {
4
try {
5
await fs.access(path);
6
console.log('File exists!');
7
} catch (error) {
8
console.error(error.message);
9
}
10
};
11
12
fileExists('./path/to/file.txt');