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
Watching Files for Changes with Node.js
📖 Scenario: You are building a simple Node.js script that watches a specific file for any changes. This is useful when you want your program to automatically react whenever the file content updates, like reloading configuration or processing new data.
🎯 Goal: Create a Node.js script that watches a file named data.txt in the current folder. When the file changes, the script should print a message indicating the file was updated.
📋 What You'll Learn
Create a variable for the file path data.txt
Create a configuration variable for the watch options
Use fs.watch to watch the file for changes
Add a callback function that logs a message when the file changes
💡 Why This Matters
🌍 Real World
Watching files for changes is useful in development tools, live reload servers, and automation scripts that need to react immediately when files update.
💼 Career
Many backend and DevOps roles require knowledge of file system watchers to build efficient workflows and monitoring tools.
Progress0 / 4 steps
1
Set up the file path variable
Create a constant variable called filePath and set it to the string './data.txt'.
Node.js
Hint
Use const to create a variable that holds the file path string.
2
Add watch options configuration
Create a constant variable called watchOptions and set it to an object with the property persistent set to true.
Node.js
Hint
The persistent option keeps the process running while watching.
3
Use fs.watch to watch the file
Import the fs module using import fs from 'fs';. Then use fs.watch with filePath, watchOptions, and a callback function with parameters eventType and filename.
Node.js
Hint
Use ES module import syntax and pass the correct arguments to fs.watch.
4
Log a message when the file changes
Inside the fs.watch callback, add an if statement that checks if eventType is 'change'. If true, log the message File data.txt was updated using console.log.
Node.js
Hint
Use a strict equality check and console.log inside the callback.
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
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.
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.
Final Answer:
To monitor changes in files or directories and react automatically -> Option C
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
Step 1: Identify correct function and parameters
fs.watch takes the filename and a callback with two parameters: eventType and filename.
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.
Final Answer:
fs.watch('example.txt', (eventType, filename) => { console.log(eventType); }); -> Option B
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
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.
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).
Final Answer:
Callback parameters are incorrect; should be (eventType, filename) -> Option D
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
Step 1: Understand event types for directory watching
When watching a directory, the rename event indicates a file was added or removed.
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.
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.
Final Answer:
fs.watch('logs', (eventType, filename) => { if (eventType === 'rename' && filename) { console.log(`New file: ${filename}`); } }); -> Option A
Quick Check:
Use 'rename' event and check filename for new files [OK]
Hint: Use 'rename' event to detect new files in directory [OK]