Registry / devops / watch-detector

watch-detector

JSON →
library1.0.2jsnpmunverified

The `watch-detector` utility identifies and selects the optimal file watcher mechanism for use with the `sane` library. It prioritizes a valid `watchman` installation on the system, falling back to Node.js's built-in watcher if `watchman` is unavailable or not correctly configured. The current stable version is 1.0.2. Release cadence appears sporadic, with maintenance updates typically driven by upstream `sane` or `watchman` compatibility issues. Its primary differentiator is abstracting the complex logic for choosing between `watchman` and Node's native file system watchers, simplifying `sane` configuration for applications that require robust and performant file monitoring, such as build tools or development servers (e.g., Ember CLI). It aims to provide the best possible performance while offering a reliable fallback, enabling developers to integrate efficient file system observation without needing to implement manual detection logic.

npm install watch-detector
INSTALL
IMPORT
SIG · WATCH-DETECTOR
W
watch-detector
devopsjavascriptv1.0.2
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

WatchDetector
import WatchDetector from 'watch-detector';
const WatchDetector = require('watch-detector');
While CommonJS `require` works, ES module `import` is preferred in modern Node.js environments. The library primarily provides a default export.

This quickstart demonstrates how to instantiate `WatchDetector`, use it to find the best `sane` watcher option, and then set up a `sane` instance to monitor a directory for changes. It includes a simple file creation to trigger the watcher.

import WatchDetector from 'watch-detector'; import sane from 'sane'; import path from 'path'; import { fileURLToPath } from 'url'; const __dirname = path.dirname(fileURLToPath(import.meta.url)); const projectRoot = path.resolve(__dirname, 'temp-project'); // Replace with your actual project root // Ensure a directory exists for sane to watch import fs from 'fs'; if (!fs.existsSync(projectRoot)) { fs.mkdirSync(projectRoot, { recursive: true }); } // Instantiate the detector. Optional 'ui' and 'fs' instances can be passed. // For simplicity, we'll use defaults here. const detector = new WatchDetector(); const saneOptions = { glob: ['**/*.js', '**/*.css'], // Only watch JS and CSS files ignored: ['node_modules/**'] // Ignore node_modules }; async function setupWatcher() { try { // findBestWatcherOption returns an object with `watcher` key (e.g., 'watchman' or 'node') const options = await detector.findBestWatcherOption(saneOptions); console.log(`Detected best watcher: ${options.watcher}`); const watcher = sane(projectRoot, options); watcher.on('change', function (filepath, root, stat) { console.log('file changed', filepath, root, stat ? stat.mtime : ''); }); watcher.on('add', function (filepath, root, stat) { console.log('file added', filepath, root, stat ? stat.mtime : ''); }); watcher.on('delete', function (filepath, root) { console.log('file deleted', filepath, root); }); console.log(`Watching ${projectRoot} with ${options.watcher} watcher...`); // To demonstrate, create a file after a delay setTimeout(() => { const filePath = path.join(projectRoot, 'test-file.js'); fs.writeFileSync(filePath, '// This is a test file\nconsole.log("Hello");'); console.log(`Created ${filePath}`); }, 2000); // Clean up after 5 seconds setTimeout(() => { watcher.close(); console.log('Watcher closed.'); // fs.rmSync(projectRoot, { recursive: true, force: true }); // Uncomment to clean up temp dir }, 5000); } catch (error) { console.error('Error setting up watcher:', error); } } setupWatcher();
Debug
Known issues
breakingThe warning message "Could not start watchman" was removed in version 1.0.0. Applications that previously relied on this specific warning for `watchman` failure detection will no longer receive it and may need to implement alternative error handling for `sane`'s watcher initialization.
fix
Review `sane`'s error handling and events. Instead of relying on `watch-detector`'s internal warning, monitor the `sane` watcher's lifecycle and potential error events (e.g., 'error' event on the `sane` watcher instance) to detect `watchman` or other watcher failures.
affects: >=1.0.0
gotchaThis package acts as an intermediary for `sane`. While it detects the 'best' watcher, underlying `watchman` issues (e.g., outdated version, incorrect permissions, system limits) can still cause `sane` to fail or behave unexpectedly. `watch-detector` helps select, but doesn't guarantee, a flawless `watchman` setup.
fix
Ensure `watchman` is installed, up-to-date, and correctly configured on the operating system. Check `watchman --version` and refer to the `watchman` documentation for troubleshooting common installation or permission issues. Monitor `sane`'s error events closely.
affects: >=0.1.0
gotchaThe README mentions `fs-events` as 'future options'. This indicates that `fs-events` is not currently supported as a watcher option by `watch-detector` and attempting to configure it will likely result in an unsupported watcher error or fallback to less efficient options.
fix
Do not attempt to configure `watch-detector` to use `fs-events`. Rely on the `watchman` or `node` watcher options as provided by `findBestWatcherOption`. If `fs-events` is critical for your use case, you may need to use `sane` directly and configure `fs-events` manually, bypassing `watch-detector`.
affects: >=0.1.0
Errors
Common errors & fixes
Error: watchman watcher failed to start
The `watchman` daemon or client could not be initialized by `sane`, likely due to an issue with the `watchman` installation, configuration, or system resources (e.g., too many watches).
fix
Verify `watchman` is installed and running (`watchman --version`, `watchman status`). Check `watchman` logs for errors. Ensure sufficient system resources (e.g., increase `fs.inotify.max_user_watches` on Linux). Reinstall `watchman` if necessary.
Error: ENOSPC: System limit for number of file watchers reached
The operating system's limit on the number of files that can be watched simultaneously has been exceeded, a common issue when `node`'s default watcher is used on large projects.
fix
Increase the system limit for file watchers (e.g., on Linux: `echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p`). Consider using `watchman` if not already, as it's more efficient with system resources for large watch sets.
Upgrade
Version history
1.0.2latest on npm
Audit
Dependencies
sanerequiredThis library is designed to provide optimal watcher options specifically for the `sane` package.
Agent activity
7 hits · last 30 days
node
6
OpenAI (training)
1
Resources
watch-detector — npm install watch-detector · libregistry