File Change Watcher

Difficulty: Medium · Topics: File IO, Events, Observer Pattern

Difficulty: Medium  |  Tags: File IO, Events, Observer Pattern

Description

Implement a file system watcher that monitors a directory for changes (file created, modified, deleted) and invokes registered callbacks when events occur.

Implement:

FileWatcher
  watch(directoryPath)                                   — start watching
  on(eventType, callback)                                — register listener
  stop()                                                 — stop watching

Event types: "created", "modified", "deleted"
Callback receives: { eventType, filePath, timestamp }

Examples

watcher = new FileWatcher()
watcher.watch("/var/logs")

watcher.on("created", (event) => {
    print("New file: " + event.filePath)     // "New file: /var/logs/app.log"
})

watcher.on("modified", (event) => {
    print("Changed: " + event.filePath)
})

// When a new file is created in /var/logs → callback fires
// When a file is modified → callback fires
// When a file is deleted → callback fires

watcher.stop()   // cleanup

Constraints

Hints

Hint 1

In Java, use java.nio.file.WatchService. In Node.js, use fs.watch(). In Go, use fsnotify.

Follow-up

Practice this problem

Related problems