Function
chokidar(obj, path = '')
Wraps an object and returns a proxied version that emits events on changes. Supports:
- Plain objects
- Arrays
- Maps
- Sets
Parameters:
obj– The object, array, Map, or Set to watch.path– Optional string indicating the root path (useful for nested structures).
Returns:
A proxied version of obj that emits events for any changes.
Events
The returned proxied object supports .on(event, callback) using an internal EventEmitter.
Supported Events
| Event | When It Fires | Arguments |
|---|---|---|
add |
A new property, array element, Map key, or Set value is added | (path, oldValue, newValue) |
update |
An existing property, array element, or Map key is updated | (path, oldValue, newValue) |
delete |
A property, array element, Map key, or Set value is removed | (path, oldValue) |
clear |
Map.clear() or Set.clear() is called |
(path, oldSnapshot) |
Notes:
- For nested objects,
pathautomatically represents the full path (e.g.,user.address.city). - Arrays emit
updateevents for structural methods (push,pop,shift,unshift,splice,sort,reverse) with the updated array state. - Maps emit events for
set,delete, andclear. - Sets emit events for
add,delete, andclear.
Example Usage
1import { chokidar } from "hbh-nodes";3const data = {4 user: { name: "Alice", age: 25 },5 items: [1, 2, 3],6 settings: new Map([['theme', 'dark']])7};9const watched = chokidar(data);11// Listen to updates12watched.user.on('update', (path, oldVal, newVal) => {13 console.log(`Updated ${path}:`, oldVal, '→', newVal);14});16watched.user.name = "Bob"; 17// Console: Updated user.name: Alice → Bob19// Listen to array changes20watched.items.on('update', (path, oldVal, newVal) => {21 console.log(`Array updated at ${path}:`, oldVal, '→', newVal);22});24watched.items.push(4); 25// Console: Array updated at items: [1,2,3] → [1,2,3,4]27// Listen to Map changes28watched.settings.on('add', (path, _, newVal) => {29 console.log(`Added to ${path}:`, newVal);30});32watched.settings.set('language', 'en'); 33// Console: Added to settings.get(language): en
Features
- Deep Observation: Nested objects, arrays, Maps, and Sets are automatically wrapped with proxies.
- Full Event Coverage: Supports add, update, delete, and clear operations for all types.
- Path Tracking: Full paths are emitted for changes, even in deeply nested structures.
- Array Method Support: Emits events for mutating methods (
push,pop, etc.). - Map/Set Support: Monitors additions, deletions, and clearing operations.
Notes
- This implementation uses
Proxyobjects; thus, it requires modern JavaScript environments. - Event listeners are attached via the
.on()method. - Useful for reactive data structures, state management, and change tracking in complex objects.