Conduitry / cheap-watch

If it works, why use something else? // Mirror of https://git.chor.date/Conduitry/cheap-watch
https://conduitry.dev/cheap-watch
MIT License
69 stars 4 forks source link
async asynchronous file file-watcher watch watcher

Cheap Watch: If it works, why use something else?

npm version Build Status

Cheap Watch is a small, simple, dependency-free, cross-platform file system watcher for Node.js 8+.

Constructor

new CheapWatch({ dir, filter, watch = true, debounce = 10 })

Methods

init()

Initialize the watcher, traverse the directory to find the initial files and directories, and set up watchers to look for changes.

This returns a Promise that resolves once the initial contents of the directory have been traversed and all of the watchers have been set up.

close()

Close all FSWatcher instances, and stop watching for file changes.

Properties

paths

A Map of the watched files and directories. Each key is a relative path from the CheapWatch's dir, and each value is a Stats object for the file or directory. Paths are always separated by forward slashes, regardless of platform. This Map is kept up to date as files are changed on disk.

You can use stats.isFile() and stats.isDirectory() to determine whether something is a file or a directory.

Events

A CheapWatch is an EventEmitter, and emits two events to report a new, updated, or deleted file or directory.

+ { path, stats, isNew }

A + event is emitted whenever a watched file or directory is created or updated. It's emitted with an object containing a path string, a stats object, and an isNew boolean which will be true for newly created files and directories and false for updated ones.

- { path, stats }

A - event is emitted whenever a watched file or directory is deleted. It's emitted with an object containing a path string and a stats object. stats will be the most recent Stats collected for the file or directory before it was deleted.

Usage

import CheapWatch from 'cheap-watch';

const watch = new CheapWatch({ dir, /* ... */ });

await watch.init();

for (const [path, stats] of watch.paths) {
    /* ... */
}

watch.on('+', ({ path, stats, isNew }) => { /* ... */ });
watch.on('-', ({ path, stats }) => { /* ... */ });

License

MIT