EN
Node.js - check if file exists
0 points
In this article, we would like to show you how to check if file exists in Node.js.
Quick solution:
xxxxxxxxxx
1
if (fs.existsSync(path)) {
2
// do some action
3
}
In this example, we use fs.existsSync()
method inside try-catch
block to check if the file exists and print the result
in the console.
xxxxxxxxxx
1
const fs = require('fs');
2
3
const path = './file.txt';
4
5
try {
6
if (fs.existsSync(path)) {
7
console.log("file exists");
8
} else {
9
console.log("file doesn't exist");
10
}
11
} catch (err) {
12
console.error(err);
13
}