In this short tip post, we will learn how to check if a file exists in the filesystem using Node.js file system (fs) module.
Objective
Figuring out the best way to check the existence of a file in a system using the native file system module of Node.
Approach
One of the simplest approach to check whether the file exists or not is by using the readFile() function. However, this function does open the file descriptor and takes some memory too.
If you just want to check the file existences in the system, I highly recommend the access() function.
Code
Here is the code.
const fs = require('fs');
const path = './config.js';
fs.access(path, fs.F_OK, (err) => {
if (err) {
console.error(err);
return;
}
// file exists
});
const path = './config.js';
fs.access(path, fs.F_OK, (err) => {
if (err) {
console.error(err);
return;
}
// file exists
});
If you want to avoid callback, we can always use promises and async/await. Like this.
const fs = require('fs')
function fileExist(filePath) {
return new Promise((resolve, reject) => {
fs.access(filePath, fs.F_OK, (err) => {
if (err) {
console.error(err)
return reject(err);
}
//file exists
resolve();
})
});
}
const path = './file.txt';
async function main() {
let existFlag = await fileExist(path);
}
function fileExist(filePath) {
return new Promise((resolve, reject) => {
fs.access(filePath, fs.F_OK, (err) => {
if (err) {
console.error(err)
return reject(err);
}
//file exists
resolve();
})
});
}
const path = './file.txt';
async function main() {
let existFlag = await fileExist(path);
}
Love Node.js? Check out our vast amount of Node.js articles and tutorials.
I got
{ [Error: ENOENT: no such file or directory, access ‘config.js’]
errno: -2,
code: ‘ENOENT’,
syscall: ‘access’,
path: ‘config.js’ }
after using your code