We check if a file exists and get its details to decide what to do next, like reading or writing it safely.
Checking file existence and stats in Node.js
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
Node.js
import { promises as fs } from 'fs'; // Check if file exists try { await fs.access('path/to/file'); // File exists } catch { // File does not exist } // Get file stats const stats = await fs.stat('path/to/file');
Use fs.access to check if a file can be accessed (exists and permissions).
Use fs.stat to get detailed info like size, creation date, and type.
Examples
Node.js
import { promises as fs } from 'fs'; async function checkFile() { try { await fs.access('example.txt'); console.log('File exists'); } catch { console.log('File does not exist'); } } checkFile();
Node.js
import { promises as fs } from 'fs'; async function showStats() { const stats = await fs.stat('example.txt'); console.log(`Size: ${stats.size} bytes`); console.log(`Is file: ${stats.isFile()}`); console.log(`Created: ${stats.birthtime}`); } showStats();
Sample Program
This program checks if 'test.txt' exists. If yes, it prints its size, confirms it is a file, and shows last modified time. If not, it says the file does not exist.
Node.js
import { promises as fs } from 'fs'; async function checkAndShow() { const path = 'test.txt'; try { await fs.access(path); const stats = await fs.stat(path); console.log(`File '${path}' exists.`); console.log(`Size: ${stats.size} bytes`); console.log(`Is file: ${stats.isFile()}`); console.log(`Last modified: ${stats.mtime}`); } catch { console.log(`File '${path}' does not exist.`); } } checkAndShow();
Important Notes
Always use try/catch with fs.access because it throws if file is missing.
fs.stat returns an object with many useful methods like isFile() and isDirectory().
Use await to handle these async calls cleanly.
Summary
Use fs.access to check if a file exists safely.
Use fs.stat to get file details like size and type.
Handle errors with try/catch to avoid crashes.
Practice
1. Which Node.js method is best to check if a file exists without throwing an error?
easy
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]
Hint: Use fs.access to check file existence safely [OK]
Common Mistakes:
- Using fs.readFile which throws error if file missing
- Trying fs.writeFile which creates or overwrites file
- Using fs.open without error handling
2. Which of the following is the correct syntax to get file stats synchronously in Node.js?
easy
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]
Hint: Sync methods end with Sync, like fs.statSync [OK]
Common Mistakes:
- Confusing async fs.stat with sync fs.statSync
- Using non-existent methods like fs.getStatsSync
- Missing parentheses for function call
3. What will the following code output if 'example.txt' exists and is a file of size 1024 bytes?
const fs = require('fs');
fs.stat('example.txt', (err, stats) => {
if (err) return console.error('Error');
console.log(stats.isFile(), stats.size);
});medium
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]
Hint: stats.isFile() true means file exists, size shows bytes [OK]
Common Mistakes:
- Assuming stats.size is undefined
- Confusing isFile() with isDirectory()
- Not handling error callback properly
4. Identify the error in this code snippet that checks if a file exists:
const fs = require('fs');
try {
fs.access('data.txt');
console.log('File exists');
} catch (err) {
console.log('File does not exist');
}medium
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]
Hint: Async functions need callbacks or await, not try/catch alone [OK]
Common Mistakes:
- Assuming try/catch works with async without await
- Ignoring callback parameter in fs.access
- Thinking fs.access does not check existence
5. You want to write a function that returns true if a given path is a directory and exists, false otherwise. Which code snippet correctly implements this using Node.js synchronous methods?
hard
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]
Hint: Use try/catch with fs.statSync and isDirectory() to check safely [OK]
Common Mistakes:
- Not handling errors for missing paths
- Checking isFile() instead of isDirectory()
- Using fs.accessSync without try/catch
