File Existence and Stats with fs.stat() and fs.access()
You'll learn how to check whether files exist and retrieve detailed information about them using Node.js.
Why Check File Existence?
Before reading, writing, or modifying files, you often need to verify they exist or gather metadata about them. Node.js provides two primary methods: fs.access() for existence checks and fs.stat() for detailed file information.
Checking Existence with fs.access()
fs.access() tests whether a file exists and whether your program has permission to read or write it. Think of it like knocking on a door to see if anyone's home before entering.
import fs from 'fs/promises';
// Check if file exists and is readable
try {
await fs.access('data.txt', fs.constants.R_OK);
console.log('File exists and is readable');
} catch {
console.log('File does not exist or is not readable');
}
Retrieving Metadata with fs.stat()
fs.stat() returns an object containing detailed file information: size, creation date, modification date, and whether it's a file or directory.
import fs from 'fs/promises';
const stats = await fs.stat('data.txt');
console.log('Size:', stats.size, 'bytes');
console.log('Created:', stats.birthtime);
console.log('Modified:', stats.mtime);
console.log('Is file:', stats.isFile());
console.log('Is directory:', stats.isDirectory());
When to Use Which
Use fs.access() for simple existence checks before operations. Use fs.stat() when you need file details like size or timestamps. Both methods have promise-based versions (from fs/promises) and throw errors if the file doesn't exist.
Key Takeaway: Use fs.access() to verify file existence and permissions, and fs.stat() to retrieve detailed metadata like size, timestamps, and file type before performing file operations.