Bird
Raised Fist0
Node.jsframework~10 mins

Checking file existence and stats in Node.js - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Checking file existence and stats
Start
Call fs.stat(path)
Does file exist?
Yes No
Get stats
Use stats
End
This flow shows how Node.js checks if a file exists by calling fs.stat, then either gets file stats or handles the error if the file is missing.
Execution Sample
Node.js
import { stat } from 'node:fs/promises';

async function checkFile(path) {
  try {
    const stats = await stat(path);
    return stats.isFile();
  } catch {
    return false;
  }
}
This async function checks if a file exists at the given path and returns true if it is a file, false otherwise.
Execution Table
StepActionEvaluationResult
1Call stat(path)Does file exist at path?Yes or No
2If YesRetrieve stats objectstats object with file info
3Call stats.isFile()Is it a file?true or false
4If No (error thrown)Catch errorReturn false
5Return resulttrue if file, false if notFunction returns boolean
💡 Function ends after returning true or false based on file existence and type
Variable Tracker
VariableStartAfter stat callAfter catchFinal
path'some/path.txt''some/path.txt''some/path.txt''some/path.txt'
statsundefinedstats objectundefinedstats object or undefined
resultundefinedundefinedfalsetrue or false
Key Moments - 3 Insights
Why do we use try/catch around stat()?
Because stat() throws an error if the file does not exist, so try/catch lets us handle that case gracefully (see execution_table step 4).
What does stats.isFile() check?
It checks if the path points to a regular file, not a directory or other type (see execution_table step 3).
Why return false in the catch block?
Because an error means the file doesn't exist or can't be accessed, so returning false signals no valid file (see execution_table step 4).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what happens at step 3?
ARetrieve stats object
BCheck if stats is a file
CCatch error if file missing
DReturn false
💡 Hint
Refer to execution_table row with Step 3 describing stats.isFile() check
At which step does the function handle the file not existing?
AStep 2
BStep 3
CStep 4
DStep 5
💡 Hint
Look at execution_table row 4 where catch handles errors
If the file exists but is a directory, what will the function return?
Afalse
Btrue
Cthrows error
Dundefined
💡 Hint
Check variable 'result' after stats.isFile() returns false for directories
Concept Snapshot
Use fs.stat(path) inside try/catch to check file existence.
If stat succeeds, use stats.isFile() to confirm it's a file.
If stat throws error, file doesn't exist; return false.
This async pattern safely checks file presence and type.
Full Transcript
This lesson shows how to check if a file exists and get its stats in Node.js using the fs/promises module. The key function is stat(path), which returns file info if the file exists or throws an error if it doesn't. We use try/catch to handle this error. If stat succeeds, we call stats.isFile() to check if the path is a file. The function returns true if it is a file, otherwise false. This approach avoids crashes and clearly signals file presence.

Practice

(1/5)
1. Which Node.js method is best to check if a file exists without throwing an error?
easy
A. fs.writeFile
B. fs.readFile
C. fs.open
D. fs.access

Solution

  1. Step 1: Understand file existence check methods

    fs.access is designed to check file accessibility without opening or reading it.
  2. Step 2: Compare with other methods

    fs.readFile reads content, fs.open opens file descriptor, fs.writeFile writes data. These are not meant for existence check.
  3. Final Answer:

    fs.access -> Option D
  4. Quick 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
A. fs.statSync('file.txt')
B. fs.stat('file.txt')
C. fs.getStatsSync('file.txt')
D. fs.fileStats('file.txt')

Solution

  1. Step 1: Identify synchronous stat method

    fs.statSync is the synchronous method to get file stats.
  2. Step 2: Check other options

    fs.stat is asynchronous, others are invalid method names.
  3. Final Answer:

    fs.statSync('file.txt') -> Option A
  4. Quick 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
A. true 1024
B. false 1024
C. true undefined
D. Error

Solution

  1. Step 1: Understand fs.stat callback

    If file exists, err is null and stats object contains file info.
  2. Step 2: Check stats properties

    stats.isFile() returns true if it is a file, stats.size returns file size in bytes.
  3. Final Answer:

    true 1024 -> Option A
  4. Quick 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
A. fs.access does not check file existence
B. fs.access is asynchronous and needs a callback or promise
C. Try/catch cannot catch errors in Node.js
D. console.log syntax is incorrect

Solution

  1. Step 1: Check fs.access usage

    fs.access is asynchronous and requires a callback or promise to handle errors.
  2. Step 2: Understand try/catch with async

    Try/catch does not catch errors from async calls without await or callback handling.
  3. Final Answer:

    fs.access is asynchronous and needs a callback or promise -> Option B
  4. Quick 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
A. function isDirectory(path) { if (fs.statSync(path).isDirectory()) return true; else return false; }
B. function isDirectory(path) { return fs.accessSync(path) && fs.statSync(path).isDirectory(); }
C. function isDirectory(path) { try { return fs.statSync(path).isDirectory(); } catch { return false; } }
D. function isDirectory(path) { try { return fs.existsSync(path) && fs.statSync(path).isFile(); } catch { return false; } }

Solution

  1. Step 1: Check for existence and directory type safely

    Using fs.statSync inside try/catch handles missing path errors and checks if it's a directory.
  2. Step 2: Analyze other options

    function isDirectory(path) { return fs.accessSync(path) && fs.statSync(path).isDirectory(); } misuses fs.accessSync without 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.
  3. Final Answer:

    function isDirectory(path) { try { return fs.statSync(path).isDirectory(); } catch { return false; } } -> Option C
  4. Quick 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