Challenge - 5 Problems
File System Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this Node.js code snippet?
Consider the following code that checks if a file exists and prints its size in bytes:
Node.js
import { promises as fs } from 'fs'; async function checkFile() { try { await fs.access('example.txt'); const stats = await fs.stat('example.txt'); console.log(`Size: ${stats.size}`); } catch { console.log('File does not exist'); } } checkFile();
Attempts:
2 left
💡 Hint
Check what fs.access and fs.stat do and how errors are handled in async/await.
✗ Incorrect
The code uses fs.access to check if the file exists. If it does, fs.stat returns stats including size. If the file is missing, the catch block prints 'File does not exist'.
❓ component_behavior
intermediate1:30remaining
What happens when using fs.existsSync to check a file synchronously?
Given this code snippet:
Node.js
import fs from 'fs'; if (fs.existsSync('data.json')) { console.log('File found'); } else { console.log('File missing'); }
Attempts:
2 left
💡 Hint
Check the behavior of fs.existsSync in Node.js.
✗ Incorrect
fs.existsSync returns true if the file exists, false otherwise. It does not throw errors.
📝 Syntax
advanced2:00remaining
Which option correctly uses fs.promises.stat to get file stats?
Choose the code snippet that correctly gets file stats asynchronously and logs the file size:
Attempts:
2 left
💡 Hint
Remember that fs.promises methods return promises and do not use callbacks.
✗ Incorrect
Option D correctly awaits the promise returned by fs.promises.stat and accesses size. Option D and D incorrectly mix callbacks with promises. Option D does not await the promise, so stats.size is undefined.
🔧 Debug
advanced2:00remaining
Why does this code throw an error when checking file stats?
Analyze this code snippet:
Node.js
import fs from 'fs'; fs.stat('missing.txt', (err, stats) => { if (stats.size > 0) { console.log('File has content'); } });
Attempts:
2 left
💡 Hint
What happens if the file does not exist? What is the value of stats?
✗ Incorrect
If the file is missing, err is set and stats is undefined. Accessing stats.size causes a TypeError.
🧠 Conceptual
expert2:30remaining
What is the difference between fs.access and fs.stat when checking file existence?
Select the most accurate statement about fs.access and fs.stat:
Attempts:
2 left
💡 Hint
Think about what each function is designed to do and their error behavior.
✗ Incorrect
fs.access tests if the file can be accessed with given permissions and does not return stats. fs.stat returns detailed info but throws if file is missing.