Node.js › File System & File Processing
How would you safely check if a file exists in Node.js before attempting to read it, avoiding a race condition?
IntermediateAnswer
Rather than checking existence with fs.access() or fs.exists() and then separately attempting to read the file (a pattern vulnerable to a race condition -- a TOCTOU, time-of-check to time-of-use bug -- where the file could be deleted between the check and the actual read), the recommended approach is to simply attempt the read operation directly and handle the specific 'ENOENT' (file not found) error if it occurs, since the operation and the error handling happen atomically together.
// Race-condition-prone: file could vanish between the check and the read
if (fs.existsSync(path)) { const data = fs.readFileSync(path); }
// Correct: attempt directly, handle the specific error
try {
const data = await fs.promises.readFile(path, 'utf-8');
} catch (err) {
if (err.code === 'ENOENT') { /* handle missing file specifically */ }
else throw err;
}Real-world example A configuration-loading function that previously checked fs.existsSync() before reading occasionally still threw an unexpected error in a containerized environment where a mounted config volume briefly became unavailable between the check and the read; refactoring to attempt the read directly and catch ENOENT eliminated the race condition entirely.