What if your app could avoid crashes just by checking files first?
Why Checking file existence and stats in Node.js? - Purpose & Use Cases
Start learning this pattern below
Jump into concepts and practice - no test required
Imagine you have a folder full of files and you want to know if a specific file is there and what size it is before you use it.
You try to open the file directly without checking, or you guess its size by looking at it manually.
Manually opening files without checking can cause your program to crash if the file is missing.
Guessing file details wastes time and can lead to errors, especially when files change often.
Node.js provides simple functions to check if a file exists and to get its details safely.
This means your program can handle missing files gracefully and use file information correctly every time.
const fs = require('fs'); const file = fs.readFileSync('data.txt'); // crashes if missing
const fs = require('fs'); if (fs.existsSync('data.txt')) { const stats = fs.statSync('data.txt'); console.log(`Size: ${stats.size}`); }
This lets your app work smoothly with files, avoiding crashes and making smart decisions based on file info.
Think of a photo app that checks if a picture file exists before trying to show it, so it never shows a broken image.
Manually handling files can cause crashes and errors.
Node.js offers easy ways to check file existence and get stats.
This makes file handling safe and reliable in your programs.
Practice
Solution
Step 1: Understand file existence check methods
fs.accessis designed to check file accessibility without opening or reading it.Step 2: Compare with other methods
fs.readFilereads content,fs.openopens file descriptor,fs.writeFilewrites data. These are not meant for existence check.Final Answer:
fs.access -> Option DQuick Check:
Check file existence = fs.access [OK]
- Using fs.readFile which throws error if file missing
- Trying fs.writeFile which creates or overwrites file
- Using fs.open without error handling
Solution
Step 1: Identify synchronous stat method
fs.statSyncis the synchronous method to get file stats.Step 2: Check other options
fs.statis asynchronous, others are invalid method names.Final Answer:
fs.statSync('file.txt') -> Option AQuick Check:
Synchronous file stats = fs.statSync [OK]
- Confusing async fs.stat with sync fs.statSync
- Using non-existent methods like fs.getStatsSync
- Missing parentheses for function call
const fs = require('fs');
fs.stat('example.txt', (err, stats) => {
if (err) return console.error('Error');
console.log(stats.isFile(), stats.size);
});Solution
Step 1: Understand fs.stat callback
If file exists, err is null and stats object contains file info.Step 2: Check stats properties
stats.isFile()returns true if it is a file,stats.sizereturns file size in bytes.Final Answer:
true 1024 -> Option AQuick Check:
File exists and is file = true and size = 1024 [OK]
- Assuming stats.size is undefined
- Confusing isFile() with isDirectory()
- Not handling error callback properly
const fs = require('fs');
try {
fs.access('data.txt');
console.log('File exists');
} catch (err) {
console.log('File does not exist');
}Solution
Step 1: Check fs.access usage
fs.accessis asynchronous and requires a callback or promise to handle errors.Step 2: Understand try/catch with async
Try/catch does not catch errors from async calls without await or callback handling.Final Answer:
fs.access is asynchronous and needs a callback or promise -> Option BQuick Check:
Async fs.access needs callback/promise [OK]
- Assuming try/catch works with async without await
- Ignoring callback parameter in fs.access
- Thinking fs.access does not check existence
Solution
Step 1: Check for existence and directory type safely
Usingfs.statSyncinside try/catch handles missing path errors and checks if it's a directory.Step 2: Analyze other options
function isDirectory(path) { return fs.accessSync(path) && fs.statSync(path).isDirectory(); } misusesfs.accessSyncwithout error handling; function isDirectory(path) { try { return fs.existsSync(path) && fs.statSync(path).isFile(); } catch { return false; } } checks isFile() instead of isDirectory(); function isDirectory(path) { if (fs.statSync(path).isDirectory()) return true; else return false; } lacks error handling for missing path.Final Answer:
function isDirectory(path) { try { return fs.statSync(path).isDirectory(); } catch { return false; } } -> Option CQuick Check:
Try/catch with statSync and isDirectory() = correct [OK]
- Not handling errors for missing paths
- Checking isFile() instead of isDirectory()
- Using fs.accessSync without try/catch
