使用fs.promises.readFile()读取文件时,是否有必要先调用fs.promises.access()检查文件存在性?
fs.promises.access() before fs.promises.readFile()? Great question — this is a common point of confusion when working with Node.js file system APIs, and the short answer is: you almost never need to use fs.promises.access() just to check if a file exists before reading it. Let me walk through why, and what you should do instead.
Why skipping access() is better
You avoid race conditions
Imagine this sequence: you runaccess()and confirm the file exists, but between that check and yourreadFile()call, the file gets deleted, moved, or renamed by another process. SuddenlyreadFile()will throw an error anyway, making your initialaccess()check useless. This is a classic race condition that you can't fully guard against with separate checks.It’s more efficient
Each call toaccess()andreadFile()is a separate system call to your OS. By skippingaccess(), you cut that number in half — less overhead, cleaner performance.Your code stays simpler
Instead of nesting two async operations (or chaining them withawait), you can handle all error cases in a singletry/catchblock. This makes your code easier to read and maintain.
The better approach: Directly use readFile() with error handling
Here’s a clean example of how to handle this correctly:
const fs = require('fs').promises; async function readTargetFile(filePath) { try { const fileContent = await fs.promises.readFile(filePath, 'utf8'); // Do something with the content here return fileContent; } catch (error) { if (error.code === 'ENOENT') { // Handle the "file not found" case specifically console.error('Error: The target file does not exist'); } else { // Re-throw other errors (like permission issues, invalid paths) throw error; } } }
By checking the error.code for ENOENT (the standard Unix error code for "no such file or directory"), you can specifically handle the file-missing scenario without needing a pre-check.
When might you need access()?
The only time access() makes sense is if you need to verify a file’s existence (or permissions) without immediately reading it. For example:
- You’re building a file browser UI and need to list which files exist in a directory
- You want to check if a file is writable before attempting to write to it later (though even then, you might still need to handle errors during the write operation)
But for your specific use case — reading a file and ensuring it exists — access() adds unnecessary complexity and risk.
内容的提问来源于stack exchange,提问作者Fabien Taillon

