/

Checking the Existence of a File in Node.js

Checking the Existence of a File in Node.js

In this blog post, we will explore different methods to check if a file exists in the filesystem using Node.js and the fs module. We will cover both synchronous and asynchronous approaches.

Using fs.existsSync()

The easiest way to check if a file exists in Node.js is by using the fs.existsSync() method. This method is synchronous, which means it will block the program until the file’s existence is determined.

1
2
3
4
5
6
7
8
9
10
const fs = require('fs');
const path = './file.txt';

try {
if (fs.existsSync(path)) {
// File exists
}
} catch(err) {
console.error(err);
}

Using fs.access()

Alternatively, we can check for a file’s existence in an asynchronous way using the fs.access() method. This method does not open the file, but rather checks if it exists.

1
2
3
4
5
6
7
8
9
10
11
const fs = require('fs');
const path = './file.txt';

fs.access(path, fs.F_OK, (err) => {
if (err) {
console.error(err);
return;
}

// File exists
});

Both methods achieve the same result, but the choice between them depends on whether you prefer a synchronous or asynchronous approach in your project.

Hope this guide helps you effectively check the existence of a file in Node.js!

tags: [“Node.js”, “fs module”, “file exists”, “check”, “synchronous”, “asynchronous”]