How can you check if a file exists before attempting to read it?

Question

Grade: Education Subject: Support
How can you check if a file exists before attempting to read it?
Asked by:
64 Viewed 64 Answers

Answer (64)

Best Answer
(409)
Use `fs.access()` or `fs.existsSync()` to check if a file exists before reading it. `fs.access()` checks if the file exists and if the calling process has the specified permissions. `fs.existsSync()` synchronously checks if the file exists. Example: `fs.access('myfile.txt', fs.constants.F_OK, (err) => { if (err) { console.error('File does not exist'); } else { fs.readFile('myfile.txt', 'utf8', ...); } });`