Bird
Raised Fist0
Node.jsframework~20 mins

Watching files for changes in Node.js - Practice Problems & Coding Challenges

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
Challenge - 5 Problems
🎖️
File Watcher Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What happens when you use fs.watch on a file?
Consider this Node.js code snippet using fs.watch to watch a file for changes. What will the output be when the file is modified?
Node.js
import { watch } from 'fs';

watch('example.txt', (eventType, filename) => {
  if (filename) {
    console.log(`${filename} file Changed: ${eventType}`);
  }
});
ALogs 'example.txt file Changed: change' each time the file is modified.
BLogs 'example.txt file Changed: rename' when the file content changes.
CThrows an error because fs.watch cannot watch files, only directories.
DLogs nothing because the callback is never called on file changes.
Attempts:
2 left
💡 Hint
Think about what eventType values fs.watch emits on file changes.
📝 Syntax
intermediate
2:00remaining
Identify the syntax error in this fs.watch usage
Which option contains the correct syntax to watch a file named 'log.txt' and log changes?
Node.js
import { watch } from 'fs';

watch('log.txt', (event, file) => {
  console.log(`${file} was ${event}`);
});
Awatch('log.txt', (event, file) => { console.log(`${file} was ${event}`) };
Bwatch('log.txt', (event, file) => { console.log(`${file} was ${event}`) });
Cwatch('log.txt', (event, file) => console.log(`${file} was ${event}`));
Dwatch('log.txt', (event, file) => { console.log(`${file} was ${event}`); });
Attempts:
2 left
💡 Hint
Check for missing semicolons and braces in arrow functions.
🔧 Debug
advanced
2:00remaining
Why does this fs.watch code miss some file changes?
This code watches 'data.json' but sometimes misses changes. Why?
Node.js
import { watch } from 'fs';

watch('data.json', (eventType) => {
  if (eventType === 'change') {
    console.log('File changed');
  }
});
ABecause fs.watch is not 100% reliable and may miss rapid changes.
BBecause the callback does not check the filename parameter.
CBecause the watch function requires a third argument for recursive watching.
DBecause the eventType should be compared to 'rename' instead of 'change'.
Attempts:
2 left
💡 Hint
Consider the limitations of fs.watch on different platforms.
state_output
advanced
2:00remaining
What is the output count of this watcher after multiple changes?
Given this code watching 'notes.txt', if the file is changed 3 times quickly, how many times will the console log 'notes.txt changed'?
Node.js
import { watch } from 'fs';

let count = 0;
watch('notes.txt', (eventType, filename) => {
  if (eventType === 'change') {
    count++;
    console.log(`${filename} changed`);
  }
});
AExactly 3 times, once per change.
BAt least 1 time, but possibly fewer than 3 due to event coalescing.
C0 times, because the callback is not triggered for rapid changes.
DMore than 3 times, because each change triggers multiple events.
Attempts:
2 left
💡 Hint
Think about how fs.watch batches or coalesces events on some systems.
🧠 Conceptual
expert
2:00remaining
Which statement about fs.watch and fs.watchFile is true?
Choose the correct statement about the differences between fs.watch and fs.watchFile in Node.js.
ABoth <code>fs.watch</code> and <code>fs.watchFile</code> use the same underlying mechanism and have identical performance.
B<code>fs.watchFile</code> uses OS-level events and is more efficient than <code>fs.watch</code>.
C<code>fs.watch</code> uses OS-level events and is more efficient but less consistent across platforms than <code>fs.watchFile</code>.
D<code>fs.watch</code> polls the file system periodically, while <code>fs.watchFile</code> uses native OS events.
Attempts:
2 left
💡 Hint
Consider how each function detects changes under the hood.

Practice

(1/5)
1. What is the main purpose of using fs.watch in Node.js?
easy
A. To read the content of a file once
B. To write data to a file
C. To monitor changes in files or directories and react automatically
D. To delete a file from the system

Solution

  1. Step 1: Understand the function of fs.watch

    fs.watch is designed to watch for changes in files or directories, triggering events when changes occur.
  2. Step 2: Compare with other file operations

    Reading, writing, or deleting files are different operations handled by other functions like fs.readFile, fs.writeFile, or fs.unlink.
  3. Final Answer:

    To monitor changes in files or directories and react automatically -> Option C
  4. Quick Check:

    Watching files = react to changes [OK]
Hint: Remember: watch means observe changes, not read or write [OK]
Common Mistakes:
  • Confusing watching with reading file content
  • Thinking it deletes or modifies files
  • Assuming it returns file data immediately
2. Which of the following is the correct syntax to watch a file named example.txt using fs.watch?
easy
A. fs.watch('example.txt', function(event) { console.log(event); });
B. fs.watch('example.txt', (eventType, filename) => { console.log(eventType); });
C. fs.watchFile('example.txt', (eventType, filename) => { console.log(filename); });
D. fs.watchFile('example.txt', function(filename) { console.log(filename); });

Solution

  1. Step 1: Identify correct function and parameters

    fs.watch takes the filename and a callback with two parameters: eventType and filename.
  2. Step 2: Check callback parameter correctness

    fs.watch('example.txt', (eventType, filename) => { console.log(eventType); }); correctly uses fs.watch with the right callback signature. The other options either use fs.watchFile or incorrect callback parameters.
  3. Final Answer:

    fs.watch('example.txt', (eventType, filename) => { console.log(eventType); }); -> Option B
  4. Quick Check:

    Correct syntax = fs.watch('example.txt', (eventType, filename) => { console.log(eventType); }); [OK]
Hint: Remember: fs.watch callback has (eventType, filename) parameters [OK]
Common Mistakes:
  • Using fs.watchFile instead of fs.watch
  • Using wrong callback parameters
  • Omitting filename parameter in callback
3. What will be the output when running this code if test.txt is modified?
const fs = require('fs');
fs.watch('test.txt', (eventType, filename) => {
  if (filename) {
    console.log(`${filename} file changed with event: ${eventType}`);
  } else {
    console.log('filename not provided');
  }
});
medium
A. test.txt file changed with event: change
B. filename not provided
C. SyntaxError
D. No output

Solution

  1. Step 1: Understand the callback behavior on file change

    When test.txt changes, fs.watch triggers the callback with eventType usually as 'change' and filename as 'test.txt'.
  2. Step 2: Analyze the conditional output

    Since filename is provided, the code logs the filename and event type message.
  3. Final Answer:

    test.txt file changed with event: change -> Option A
  4. Quick Check:

    File changed event logs filename and event [OK]
Hint: If filename exists, output shows file and event type [OK]
Common Mistakes:
  • Assuming filename is always undefined
  • Expecting no output on file change
  • Confusing eventType values
4. Identify the error in this code snippet that watches a file and logs changes:
const fs = require('fs');
fs.watch('log.txt', (event, file) => {
  console.log(file + ' changed');
});
medium
A. The file name string should be an absolute path
B. Missing error handling for fs.watch
C. fs.watch cannot watch files, only directories
D. Callback parameters are incorrect; should be (eventType, filename)

Solution

  1. Step 1: Recall fs.watch callback signature

    fs.watch's callback takes two arguments: the first is the event type (conventionally eventType), the second is the filename (conventionally filename). The code uses (event, file), which mismatches the standard names.
  2. Step 2: Identify the issue from options

    Callback parameters are incorrect; should be (eventType, filename) correctly states that the callback parameters are incorrect and should use (eventType, filename).
  3. Final Answer:

    Callback parameters are incorrect; should be (eventType, filename) -> Option D
  4. Quick Check:

    Correct callback params = (eventType, filename) [OK]
Hint: Use (eventType, filename) as callback parameters for clarity [OK]
Common Mistakes:
  • Using non-standard callback parameter names
  • Thinking fs.watch only works on directories
  • Assuming relative path is invalid
5. You want to watch a directory logs and print the name of any new file created inside it. Which code snippet correctly achieves this?
hard
A. fs.watch('logs', (eventType, filename) => { if (eventType === 'rename' && filename) { console.log(`New file: ${filename}`); } });
B. fs.watch('logs', (eventType) => { if (eventType === 'change') { console.log('File changed'); } });
C. fs.watchFile('logs', (curr, prev) => { console.log('Directory changed'); });
D. fs.watch('logs', () => { console.log('Something changed'); });

Solution

  1. Step 1: Understand event types for directory watching

    When watching a directory, the rename event indicates a file was added or removed.
  2. Step 2: Check for filename and event type

    fs.watch('logs', (eventType, filename) => { if (eventType === 'rename' && filename) { console.log(`New file: ${filename}`); } }); checks for rename event and ensures filename is provided before logging the new file name, which is correct.
  3. Step 3: Evaluate other options

    fs.watch('logs', (eventType) => { if (eventType === 'change') { console.log('File changed'); } }); only checks for change event and does not handle new files specifically. fs.watchFile('logs', (curr, prev) => { console.log('Directory changed'); }); uses fs.watchFile which is for files, not directories. fs.watch('logs', () => { console.log('Something changed'); }); logs on any change but does not specify new files.
  4. Final Answer:

    fs.watch('logs', (eventType, filename) => { if (eventType === 'rename' && filename) { console.log(`New file: ${filename}`); } }); -> Option A
  5. Quick Check:

    Use 'rename' event and check filename for new files [OK]
Hint: Use 'rename' event to detect new files in directory [OK]
Common Mistakes:
  • Using 'change' event to detect new files
  • Using fs.watchFile for directories
  • Not checking if filename is provided