How to capture no file error with Node.js fs.readFileSync()?

Sometimes, we want to capture no file error with Node.js fs.readFileSync().

In this article, we’ll look at how to capture no file error with Node.js fs.readFileSync().

How to capture no file error with Node.js fs.readFileSync()?

To capture no file error with Node.js fs.readFileSync(), we can use try-catch and check for the no file error in the catch with err.code.

For instance, we write

let fileContents;
try {
  fileContents = fs.readFileSync('foo.bar');
} catch (err) {
  if (err.code === 'ENOENT') {
    console.log('File not found!');
  } else {
    throw err;
  }
}

to check if err.code is 'ENOENT'.

If it is, then we know readFileSync threw an error because the 'foo.bar' file wasn’t found.

Conclusion

To capture no file error with Node.js fs.readFileSync(), we can use try-catch and check for the no file error in the catch with err.code.