Repository: paulmillr/chokidar
Branch: main
Commit: c6d772a92f30
Files: 14
Total size: 149.6 KB
Directory structure:
gitextract_tssteiwg/
├── .github/
│ ├── ISSUE_TEMPLATE/
│ │ └── bug_report.md
│ ├── funding.yml
│ └── workflows/
│ ├── release.yml
│ └── test-js.yml
├── .gitignore
├── .prettierrc.json
├── LICENSE
├── README.md
├── example.js
├── package.json
├── src/
│ ├── handler.ts
│ ├── index.test.ts
│ └── index.ts
└── tsconfig.json
================================================
FILE CONTENTS
================================================
================================================
FILE: .github/ISSUE_TEMPLATE/bug_report.md
================================================
---
name: Bug report
about: Create a report to help us improve
---
**Describe the bug**
A clear and concise description of what the bug is.
**Versions (please complete the following information):**
- Chokidar version [e.g. 3.2.1 or commit hash]
- Node version [e.g. 12.11.0, ensure you are using the latest node.js]
- OS version: [e.g. Ubuntu 19.04 or MacOS 10.15 or Windows 10]
**To Reproduce:**
Steps to reproduce the behavior. Include filename and chokidar config.
Ideally prove a problem by isolating and making it reproducible with a very short sample program, which you could paste here:
```
const chokidar = require('chokidar');
const fs = require('fs');
// One-liner for files and directories starting with 'test'
chokidar.watch('test*', {}).on('all', (event, path) => {
console.log(event, path);
});
fs.writeFileSync('test.txt', 'testing 1');
// In a comment describe expected output versus observed problem
```
Most valuable could be one or more test cases for [test.js](https://github.com/paulmillr/chokidar/blob/master/test.js) to demonstrate the problem.
**Expected behavior**
A clear and concise description of what you expect to happen.
**Additional context**
Add any other context about the problem here.
Optionally nice to know what project you are working on.
================================================
FILE: .github/funding.yml
================================================
github: paulmillr
# custom: https://paulmillr.com/funding/
================================================
FILE: .github/workflows/release.yml
================================================
name: Publish release
on:
release:
types: [created]
jobs:
release-js:
name: 'jsbt v0.4.5' # Should match commit below
uses: paulmillr/jsbt/.github/workflows/release.yml@570adcfe0ed96b477bb9b35400fb43fd9406fb47
permissions:
contents: read
id-token: write
================================================
FILE: .github/workflows/test-js.yml
================================================
name: Run TS tests
on:
- push
- pull_request
jobs:
test-ts:
name: 'jsbt v0.4.5' # Should match commit below
uses: paulmillr/jsbt/.github/workflows/test-js-matrix.yml@570adcfe0ed96b477bb9b35400fb43fd9406fb47
================================================
FILE: .gitignore
================================================
*.bak
*.log
/coverage/
/node_modules/
/test-fixtures/
/*.d.ts
/*.d.mts
/*.map
/index.js
/handler.js
/esm
/*.test.js
/*.test.mjs
================================================
FILE: .prettierrc.json
================================================
{
"printWidth": 100,
"singleQuote": true,
"trailingComma": "es5"
}
================================================
FILE: LICENSE
================================================
The MIT License (MIT)
Copyright (c) 2012 Paul Miller (https://paulmillr.com), Elan Shanker
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the “Software”), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
================================================
FILE: README.md
================================================
# Chokidar [](https://github.com/paulmillr/chokidar)
Minimal and efficient cross-platform file watching library
## Why?
There are many reasons to prefer Chokidar to raw fs.watch / fs.watchFile in 2026:
- Events are properly reported
- macOS events report filenames
- events are not reported twice
- changes are reported as add / change / unlink instead of useless `rename`
- Atomic writes are supported, using `atomic` option
- Some file editors use them
- Chunked writes are supported, using `awaitWriteFinish` option
- Large files are commonly written in chunks
- File / dir filtering is supported
- Symbolic links are supported
- Recursive watching is always supported, instead of partial when using raw events
- Includes a way to limit recursion depth
Chokidar relies on the Node.js core `fs` module, but when using
`fs.watch` and `fs.watchFile` for watching, it normalizes the events it
receives, often checking for truth by getting file stats and/or dir contents.
The `fs.watch`-based implementation is the default, which
avoids polling and keeps CPU usage down. Be advised that chokidar will initiate
watchers recursively for everything within scope of the paths that have been
specified, so be judicious about not wasting system resources by watching much
more than needed. For some cases, `fs.watchFile`, which utilizes polling and uses more resources, is used.
Made for [Brunch](https://brunch.io/) in 2012,
it is now used in [~30 million repositories](https://www.npmjs.com/browse/depended/chokidar) and
has proven itself in production environments.
- **Nov 2025 update:** v5 is out. Makes package ESM-only and increases minimum node.js requirement to v20.
- **Sep 2024 update:** v4 is out! It decreases dependency count from 13 to 1, removes
support for globs, adds support for ESM / Common.js modules, and bumps minimum node.js version from v8 to v14.
Check out [upgrading](#upgrading).
## Getting started
Install with npm:
```sh
npm install chokidar
```
Use it in your code:
```javascript
import chokidar from 'chokidar';
// One-liner for current directory
chokidar.watch('.').on('all', (event, path) => {
console.log(event, path);
});
// Extended options
// ----------------
// Initialize watcher.
const watcher = chokidar.watch('file, dir, or array', {
ignored: (path, stats) => stats?.isFile() && !path.endsWith('.js'), // only watch js files
persistent: true,
});
// Something to use when events are received.
const log = console.log.bind(console);
// Add event listeners.
watcher
.on('add', (path) => log(`File ${path} has been added`))
.on('change', (path) => log(`File ${path} has been changed`))
.on('unlink', (path) => log(`File ${path} has been removed`));
// More possible events.
watcher
.on('addDir', (path) => log(`Directory ${path} has been added`))
.on('unlinkDir', (path) => log(`Directory ${path} has been removed`))
.on('error', (error) => log(`Watcher error: ${error}`))
.on('ready', () => log('Initial scan complete. Ready for changes'))
.on('raw', (event, path, details) => {
// internal
log('Raw event info:', event, path, details);
});
// 'add', 'addDir' and 'change' events also receive stat() results as second
// argument when available: https://nodejs.org/api/fs.html#fs_class_fs_stats
watcher.on('change', (path, stats) => {
if (stats) console.log(`File ${path} changed size to ${stats.size}`);
});
// Watch new files.
watcher.add('new-file');
watcher.add(['new-file-2', 'new-file-3']);
// Get list of actual paths being watched on the filesystem
let watchedPaths = watcher.getWatched();
// Un-watch some files.
await watcher.unwatch('new-file');
// Stop watching. The method is async!
await watcher.close().then(() => console.log('closed'));
// Full list of options. See below for descriptions.
// Do not use this example!
chokidar.watch('file', {
persistent: true,
// ignore .txt files
ignored: (file) => file.endsWith('.txt'),
// watch only .txt files
// ignored: (file, _stats) => _stats?.isFile() && !file.endsWith('.txt'),
awaitWriteFinish: true, // emit single event when chunked writes are completed
atomic: true, // emit proper events when "atomic writes" (mv _tmp file) are used
// The options also allow specifying custom intervals in ms
// awaitWriteFinish: {
// stabilityThreshold: 2000,
// pollInterval: 100
// },
// atomic: 100,
interval: 100,
binaryInterval: 300,
cwd: '.',
depth: 99,
followSymlinks: true,
ignoreInitial: false,
ignorePermissionErrors: false,
usePolling: false,
alwaysStat: false,
});
```
`chokidar.watch(paths, [options])`
- `paths` (string or array of strings). Paths to files, dirs to be watched
recursively.
- `options` (object) Options object as defined below:
#### Persistence
- `persistent` (default: `true`). Indicates whether the process
should continue to run as long as files are being watched.
#### Path filtering
- `ignored` function, regex, or path. Defines files/paths to be ignored.
The whole relative or absolute path is tested, not just filename. If a function with two arguments
is provided, it gets called twice per path - once with a single argument (the path), second
time with two arguments (the path and the
[`fs.Stats`](https://nodejs.org/api/fs.html#fs_class_fs_stats)
object of that path).
- `ignoreInitial` (default: `false`). If set to `false` then `add`/`addDir` events are also emitted for matching paths while
instantiating the watching as chokidar discovers these file paths (before the `ready` event).
- `followSymlinks` (default: `true`). When `false`, only the
symlinks themselves will be watched for changes instead of following
the link references and bubbling events through the link's path.
- `cwd` (no default). The base directory from which watch `paths` are to be
derived. Paths emitted with events will be relative to this.
#### Performance
- `usePolling` (default: `false`).
Whether to use fs.watchFile (backed by polling), or fs.watch. If polling
leads to high CPU utilization, consider setting this to `false`. It is
typically necessary to **set this to `true` to successfully watch files over
a network**, and it may be necessary to successfully watch files in other
non-standard situations. Setting to `true` explicitly on MacOS overrides the
`useFsEvents` default. You may also set the CHOKIDAR_USEPOLLING env variable
to true (1) or false (0) in order to override this option.
- _Polling-specific settings_ (effective when `usePolling: true`)
- `interval` (default: `100`). Interval of file system polling, in milliseconds. You may also
set the CHOKIDAR_INTERVAL env variable to override this option.
- `binaryInterval` (default: `300`). Interval of file system
polling for binary files.
([see list of binary extensions](https://github.com/sindresorhus/binary-extensions/blob/master/binary-extensions.json))
- `alwaysStat` (default: `false`). If relying upon the
[`fs.Stats`](https://nodejs.org/api/fs.html#fs_class_fs_stats)
object that may get passed with `add`, `addDir`, and `change` events, set
this to `true` to ensure it is provided even in cases where it wasn't
already available from the underlying watch events.
- `depth` (default: `undefined`). If set, limits how many levels of
subdirectories will be traversed.
- `awaitWriteFinish` (default: `false`).
By default, the `add` event will fire when a file first appears on disk, before
the entire file has been written. Furthermore, in some cases some `change`
events will be emitted while the file is being written. In some cases,
especially when watching for large files there will be a need to wait for the
write operation to finish before responding to a file creation or modification.
Setting `awaitWriteFinish` to `true` (or a truthy value) will poll file size,
holding its `add` and `change` events until the size does not change for a
configurable amount of time. The appropriate duration setting is heavily
dependent on the OS and hardware. For accurate detection this parameter should
be relatively high, making file watching much less responsive.
Use with caution.
- _`options.awaitWriteFinish` can be set to an object in order to adjust
timing params:_
- `awaitWriteFinish.stabilityThreshold` (default: 2000). Amount of time in
milliseconds for a file size to remain constant before emitting its event.
- `awaitWriteFinish.pollInterval` (default: 100). File size polling interval, in milliseconds.
#### Errors
- `ignorePermissionErrors` (default: `false`). Indicates whether to watch files
that don't have read permissions if possible. If watching fails due to `EPERM`
or `EACCES` with this set to `true`, the errors will be suppressed silently.
- `atomic` (default: `true` if `useFsEvents` and `usePolling` are `false`).
Automatically filters out artifacts that occur when using editors that use
"atomic writes" instead of writing directly to the source file. If a file is
re-added within 100 ms of being deleted, Chokidar emits a `change` event
rather than `unlink` then `add`. If the default of 100 ms does not work well
for you, you can override it by setting `atomic` to a custom value, in
milliseconds.
### Methods & Events
`chokidar.watch()` produces an instance of `FSWatcher`. Methods of `FSWatcher`:
- `.add(path / paths)`: Add files, directories for tracking.
Takes an array of strings or just one string.
- `.on(event, callback)`: Listen for an FS event.
Available events: `add`, `addDir`, `change`, `unlink`, `unlinkDir`, `ready`,
`raw`, `error`.
Additionally `all` is available which gets emitted with the underlying event
name and path for every event other than `ready`, `raw`, and `error`. `raw` is internal, use it carefully.
- `.unwatch(path / paths)`: Stop watching files or directories.
Takes an array of strings or just one string.
- `.close()`: **async** Removes all listeners from watched files. Asynchronous, returns Promise. Use with `await` to ensure bugs don't happen.
- `.getWatched()`: Returns an object representing all the paths on the file
system being watched by this `FSWatcher` instance. The object's keys are all the
directories (using absolute paths unless the `cwd` option was used), and the
values are arrays of the names of the items contained in each directory.
### CLI
Check out third party [chokidar-cli](https://github.com/open-cli-tools/chokidar-cli),
which allows to execute a command on each change, or get a stdio stream of change events.
## Troubleshooting
Sometimes, Chokidar runs out of file handles, causing `EMFILE` and `ENOSP` errors:
- `bash: cannot set terminal process group (-1): Inappropriate ioctl for device bash: no job control in this shell`
- `Error: watch /home/ ENOSPC`
There are two things that can cause it.
1. Exhausted file handles for generic fs operations
- Can be solved by using [graceful-fs](https://www.npmjs.com/package/graceful-fs),
which can monkey-patch native `fs` module used by chokidar: `let fs = require('fs'); let grfs = require('graceful-fs'); grfs.gracefulify(fs);`
- Can also be solved by tuning OS: `echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p`.
2. Exhausted file handles for `fs.watch`
- Can't seem to be solved by graceful-fs or OS tuning
- It's possible to start using `usePolling: true`, which will switch backend to resource-intensive `fs.watchFile`
All fsevents-related issues (`WARN optional dep failed`, `fsevents is not a constructor`) are solved by upgrading to v4+.
## Changelog
- **v4 (Sep 2024):** remove glob support and bundled fsevents. Decrease dependency count from 13 to 1. Rewrite in typescript. Bumps minimum node.js requirement to v14+
- **v3 (Apr 2019):** massive CPU & RAM consumption improvements; reduces deps / package size by a factor of 17x and bumps Node.js requirement to v8.16+.
- **v2 (Dec 2017):** globs are now posix-style-only. Tons of bugfixes.
- **v1 (Apr 2015):** glob support, symlink support, tons of bugfixes. Node 0.8+ is supported
- **v0.1 (Apr 2012):** Initial release, extracted from [Brunch](https://github.com/brunch/brunch/blob/9847a065aea300da99bd0753f90354cde9de1261/src/helpers.coffee#L66)
### Upgrading
If you've used globs before and want do replicate the functionality with v4:
```js
// v3
chok.watch('**/*.js');
chok.watch('./directory/**/*');
// v4
chok.watch('.', {
ignored: (path, stats) => stats?.isFile() && !path.endsWith('.js'), // only watch js files
});
chok.watch('./directory');
// other way
import { glob } from 'node:fs/promises';
const watcher = watch(await Array.fromAsync(glob('**/*.js')));
// unwatching
// v3
chok.unwatch('**/*.js');
// v4
chok.unwatch(await Array.fromAsync(glob('**/*.js')));
```
## Also
Why was chokidar named this way? What's the meaning behind it?
> Chowkidar is a transliteration of a Hindi word meaning 'watchman, gatekeeper', चौकीदार. This ultimately comes from Sanskrit _ चतुष्क_ (crossway, quadrangle, consisting-of-four). This word is also used in other languages like Urdu as (چوکیدار) which is widely used in Pakistan and India.
## License
MIT (c) Paul Miller (<https://paulmillr.com>), see [LICENSE](LICENSE) file.
================================================
FILE: example.js
================================================
global.watcher = require('./index.js').default.watch('.', {
ignored: /node_modules|\.git/,
persistent: true,
// followSymlinks: false,
// useFsEvents: false,
// usePolling: false,
})
.on('all', (event, path) => { console.log(event, path); })
.on('ready', () => { console.log('Ready'); })
//.on('raw', console.log.bind(console, 'Raw event:'))
================================================
FILE: package.json
================================================
{
"name": "chokidar",
"description": "Minimal and efficient cross-platform file watching library",
"version": "5.0.0",
"type": "module",
"homepage": "https://github.com/paulmillr/chokidar",
"author": "Paul Miller (https://paulmillr.com)",
"files": [
"index.js",
"index.d.ts",
"handler.js",
"handler.d.ts"
],
"main": "./index.js",
"exports": {
".": {
"default": "./index.js"
},
"./handler.js": {
"default": "./handler.js"
}
},
"dependencies": {
"readdirp": "^5.0.0"
},
"devDependencies": {
"@paulmillr/jsbt": "0.4.5",
"@types/node": "24.10.1",
"prettier": "3.5.2",
"tinyspy": "3.0.2",
"typescript": "5.9.2",
"upath": "2.0.1"
},
"sideEffects": false,
"engines": {
"node": ">= 20.19.0"
},
"repository": {
"type": "git",
"url": "git+https://github.com/paulmillr/chokidar.git"
},
"bugs": {
"url": "https://github.com/paulmillr/chokidar/issues"
},
"license": "MIT",
"scripts": {
"build": "tsc",
"lint": "prettier --check src",
"format": "prettier --write src",
"test": "node index.test.js",
"test:bun1": "bun index.test.js"
},
"keywords": [
"fs",
"watch",
"watchFile",
"watcher",
"watching",
"file",
"fsevents"
],
"funding": "https://paulmillr.com/funding/"
}
================================================
FILE: src/handler.ts
================================================
import type { FSWatcher as NativeFsWatcher, Stats, WatchEventType, WatchListener } from 'node:fs';
import { watch as fs_watch, unwatchFile, watchFile } from 'node:fs';
import { realpath as fsrealpath, lstat, open, stat } from 'node:fs/promises';
import { type as osType } from 'node:os';
import * as sp from 'node:path';
import type { EntryInfo } from 'readdirp';
import type { FSWatcher, FSWInstanceOptions, Throttler, WatchHelper } from './index.js';
export type Path = string;
export const STR_DATA = 'data';
export const STR_END = 'end';
export const STR_CLOSE = 'close';
export const EMPTY_FN = (): void => {};
export const IDENTITY_FN = (val: unknown): unknown => val;
const pl = process.platform;
export const isWindows: boolean = pl === 'win32';
export const isMacos: boolean = pl === 'darwin';
export const isLinux: boolean = pl === 'linux';
export const isFreeBSD: boolean = pl === 'freebsd';
export const isIBMi: boolean = osType() === 'OS400';
export const EVENTS = {
ALL: 'all',
READY: 'ready',
ADD: 'add',
CHANGE: 'change',
ADD_DIR: 'addDir',
UNLINK: 'unlink',
UNLINK_DIR: 'unlinkDir',
RAW: 'raw',
ERROR: 'error',
} as const;
export type EventName = (typeof EVENTS)[keyof typeof EVENTS];
const EV = EVENTS;
const THROTTLE_MODE_WATCH = 'watch';
const statMethods = { lstat, stat };
const KEY_LISTENERS = 'listeners';
const KEY_ERR = 'errHandlers';
const KEY_RAW = 'rawEmitters';
const HANDLER_KEYS = [KEY_LISTENERS, KEY_ERR, KEY_RAW];
// prettier-ignore
const binaryExtensions = new Set([
'3dm', '3ds', '3g2', '3gp', '7z', 'a', 'aac', 'adp', 'afdesign', 'afphoto', 'afpub', 'ai',
'aif', 'aiff', 'alz', 'ape', 'apk', 'appimage', 'ar', 'arj', 'asf', 'au', 'avi',
'bak', 'baml', 'bh', 'bin', 'bk', 'bmp', 'btif', 'bz2', 'bzip2',
'cab', 'caf', 'cgm', 'class', 'cmx', 'cpio', 'cr2', 'cur', 'dat', 'dcm', 'deb', 'dex', 'djvu',
'dll', 'dmg', 'dng', 'doc', 'docm', 'docx', 'dot', 'dotm', 'dra', 'DS_Store', 'dsk', 'dts',
'dtshd', 'dvb', 'dwg', 'dxf',
'ecelp4800', 'ecelp7470', 'ecelp9600', 'egg', 'eol', 'eot', 'epub', 'exe',
'f4v', 'fbs', 'fh', 'fla', 'flac', 'flatpak', 'fli', 'flv', 'fpx', 'fst', 'fvt',
'g3', 'gh', 'gif', 'graffle', 'gz', 'gzip',
'h261', 'h263', 'h264', 'icns', 'ico', 'ief', 'img', 'ipa', 'iso',
'jar', 'jpeg', 'jpg', 'jpgv', 'jpm', 'jxr', 'key', 'ktx',
'lha', 'lib', 'lvp', 'lz', 'lzh', 'lzma', 'lzo',
'm3u', 'm4a', 'm4v', 'mar', 'mdi', 'mht', 'mid', 'midi', 'mj2', 'mka', 'mkv', 'mmr','mng',
'mobi', 'mov', 'movie', 'mp3',
'mp4', 'mp4a', 'mpeg', 'mpg', 'mpga', 'mxu',
'nef', 'npx', 'numbers', 'nupkg',
'o', 'odp', 'ods', 'odt', 'oga', 'ogg', 'ogv', 'otf', 'ott',
'pages', 'pbm', 'pcx', 'pdb', 'pdf', 'pea', 'pgm', 'pic', 'png', 'pnm', 'pot', 'potm',
'potx', 'ppa', 'ppam',
'ppm', 'pps', 'ppsm', 'ppsx', 'ppt', 'pptm', 'pptx', 'psd', 'pya', 'pyc', 'pyo', 'pyv',
'qt',
'rar', 'ras', 'raw', 'resources', 'rgb', 'rip', 'rlc', 'rmf', 'rmvb', 'rpm', 'rtf', 'rz',
's3m', 's7z', 'scpt', 'sgi', 'shar', 'snap', 'sil', 'sketch', 'slk', 'smv', 'snk', 'so',
'stl', 'suo', 'sub', 'swf',
'tar', 'tbz', 'tbz2', 'tga', 'tgz', 'thmx', 'tif', 'tiff', 'tlz', 'ttc', 'ttf', 'txz',
'udf', 'uvh', 'uvi', 'uvm', 'uvp', 'uvs', 'uvu',
'viv', 'vob',
'war', 'wav', 'wax', 'wbmp', 'wdp', 'weba', 'webm', 'webp', 'whl', 'wim', 'wm', 'wma',
'wmv', 'wmx', 'woff', 'woff2', 'wrm', 'wvx',
'xbm', 'xif', 'xla', 'xlam', 'xls', 'xlsb', 'xlsm', 'xlsx', 'xlt', 'xltm', 'xltx', 'xm',
'xmind', 'xpi', 'xpm', 'xwd', 'xz',
'z', 'zip', 'zipx',
]);
const isBinaryPath = (filePath: string) =>
binaryExtensions.has(sp.extname(filePath).slice(1).toLowerCase());
// TODO: emit errors properly. Example: EMFILE on Macos.
const foreach = <V extends unknown>(val: V, fn: (arg: V) => unknown) => {
if (val instanceof Set) {
val.forEach(fn);
} else {
fn(val);
}
};
const addAndConvert = (main: Record<string, unknown>, prop: string, item: unknown) => {
let container = (main as Record<string, unknown>)[prop];
if (!(container instanceof Set)) {
(main as Record<string, unknown>)[prop] = container = new Set([container]);
}
(container as Set<unknown>).add(item);
};
const clearItem = (cont: Record<string, unknown>) => (key: string) => {
const set = cont[key];
if (set instanceof Set) {
set.clear();
} else {
delete cont[key];
}
};
const delFromSet = (main: Record<string, unknown> | Set<unknown>, prop: string, item: unknown) => {
const container = (main as Record<string, unknown>)[prop];
if (container instanceof Set) {
container.delete(item);
} else if (container === item) {
delete (main as Record<string, unknown>)[prop];
}
};
const isEmptySet = (val: unknown) => (val instanceof Set ? val.size === 0 : !val);
// fs_watch helpers
// object to hold per-process fs_watch instances
// (may be shared across chokidar FSWatcher instances)
export type FsWatchContainer = {
listeners: (path: string) => void | Set<any>;
errHandlers: (err: unknown) => void | Set<any>;
rawEmitters: (ev: WatchEventType, path: string, opts: unknown) => void | Set<any>;
watcher: NativeFsWatcher;
watcherUnusable?: boolean;
};
const FsWatchInstances = new Map<string, FsWatchContainer>();
/**
* Instantiates the fs_watch interface
* @param path to be watched
* @param options to be passed to fs_watch
* @param listener main event handler
* @param errHandler emits info about errors
* @param emitRaw emits raw event data
* @returns {NativeFsWatcher}
*/
function createFsWatchInstance(
path: string,
options: Partial<FSWInstanceOptions>,
listener: WatchHandlers['listener'],
errHandler: WatchHandlers['errHandler'],
emitRaw: WatchHandlers['rawEmitter']
): NativeFsWatcher | undefined {
const handleEvent: WatchListener<string> = (rawEvent, evPath: string | null) => {
listener(path);
emitRaw(rawEvent, evPath!, { watchedPath: path });
// emit based on events occurring for files from a directory's watcher in
// case the file's watcher misses it (and rely on throttling to de-dupe)
if (evPath && path !== evPath) {
fsWatchBroadcast(sp.resolve(path, evPath), KEY_LISTENERS, sp.join(path, evPath));
}
};
try {
return fs_watch(
path,
{
persistent: options.persistent,
},
handleEvent
);
} catch (error) {
errHandler(error);
return undefined;
}
}
/**
* Helper for passing fs_watch event data to a collection of listeners
* @param fullPath absolute path bound to fs_watch instance
*/
const fsWatchBroadcast = (
fullPath: Path,
listenerType: string,
val1?: unknown,
val2?: unknown,
val3?: unknown
) => {
const cont = FsWatchInstances.get(fullPath);
if (!cont) return;
foreach(cont[listenerType as keyof typeof cont], (listener: any) => {
listener(val1, val2, val3);
});
};
export interface WatchHandlers {
listener: (path: string) => void;
errHandler: (err: unknown) => void;
rawEmitter: (ev: WatchEventType, path: string, opts: unknown) => void;
}
/**
* Instantiates the fs_watch interface or binds listeners
* to an existing one covering the same file system entry
* @param path
* @param fullPath absolute path
* @param options to be passed to fs_watch
* @param handlers container for event listener functions
*/
const setFsWatchListener = (
path: string,
fullPath: string,
options: Partial<FSWInstanceOptions>,
handlers: WatchHandlers
) => {
const { listener, errHandler, rawEmitter } = handlers;
let cont = FsWatchInstances.get(fullPath);
let watcher: NativeFsWatcher | undefined;
if (!options.persistent) {
watcher = createFsWatchInstance(path, options, listener, errHandler, rawEmitter);
if (!watcher) return;
return watcher.close.bind(watcher);
}
if (cont) {
addAndConvert(cont, KEY_LISTENERS, listener);
addAndConvert(cont, KEY_ERR, errHandler);
addAndConvert(cont, KEY_RAW, rawEmitter);
} else {
watcher = createFsWatchInstance(
path,
options,
fsWatchBroadcast.bind(null, fullPath, KEY_LISTENERS),
errHandler, // no need to use broadcast here
fsWatchBroadcast.bind(null, fullPath, KEY_RAW)
);
if (!watcher) return;
watcher.on(EV.ERROR, async (error: Error & { code: string }) => {
const broadcastErr = fsWatchBroadcast.bind(null, fullPath, KEY_ERR);
if (cont) cont.watcherUnusable = true; // documented since Node 10.4.1
// Workaround for https://github.com/joyent/node/issues/4337
if (isWindows && error.code === 'EPERM') {
try {
const fd = await open(path, 'r');
await fd.close();
broadcastErr(error);
} catch (err) {
// do nothing
}
} else {
broadcastErr(error);
}
});
cont = {
listeners: listener,
errHandlers: errHandler,
rawEmitters: rawEmitter,
watcher,
};
FsWatchInstances.set(fullPath, cont);
}
// const index = cont.listeners.indexOf(listener);
// removes this instance's listeners and closes the underlying fs_watch
// instance if there are no more listeners left
return () => {
delFromSet(cont, KEY_LISTENERS, listener);
delFromSet(cont, KEY_ERR, errHandler);
delFromSet(cont, KEY_RAW, rawEmitter);
if (isEmptySet(cont.listeners)) {
// Check to protect against issue gh-730.
// if (cont.watcherUnusable) {
cont.watcher.close();
// }
FsWatchInstances.delete(fullPath);
HANDLER_KEYS.forEach(clearItem(cont));
// @ts-ignore
cont.watcher = undefined;
Object.freeze(cont);
}
};
};
// fs_watchFile helpers
// object to hold per-process fs_watchFile instances
// (may be shared across chokidar FSWatcher instances)
const FsWatchFileInstances = new Map<string, any>();
/**
* Instantiates the fs_watchFile interface or binds listeners
* to an existing one covering the same file system entry
* @param path to be watched
* @param fullPath absolute path
* @param options options to be passed to fs_watchFile
* @param handlers container for event listener functions
* @returns closer
*/
const setFsWatchFileListener = (
path: Path,
fullPath: Path,
options: Partial<FSWInstanceOptions>,
handlers: Pick<WatchHandlers, 'rawEmitter' | 'listener'>
): (() => void) => {
const { listener, rawEmitter } = handlers;
let cont = FsWatchFileInstances.get(fullPath);
// let listeners = new Set();
// let rawEmitters = new Set();
const copts = cont && cont.options;
if (copts && (copts.persistent < options.persistent! || copts.interval > options.interval!)) {
// "Upgrade" the watcher to persistence or a quicker interval.
// This creates some unlikely edge case issues if the user mixes
// settings in a very weird way, but solving for those cases
// doesn't seem worthwhile for the added complexity.
// listeners = cont.listeners;
// rawEmitters = cont.rawEmitters;
unwatchFile(fullPath);
cont = undefined;
}
if (cont) {
addAndConvert(cont, KEY_LISTENERS, listener);
addAndConvert(cont, KEY_RAW, rawEmitter);
} else {
// TODO
// listeners.add(listener);
// rawEmitters.add(rawEmitter);
cont = {
listeners: listener,
rawEmitters: rawEmitter,
options,
watcher: watchFile(fullPath, options, (curr, prev) => {
foreach(cont.rawEmitters, (rawEmitter) => {
rawEmitter(EV.CHANGE, fullPath, { curr, prev });
});
const currmtime = curr.mtimeMs;
if (curr.size !== prev.size || currmtime > prev.mtimeMs || currmtime === 0) {
foreach(cont.listeners, (listener) => listener(path, curr));
}
}),
};
FsWatchFileInstances.set(fullPath, cont);
}
// const index = cont.listeners.indexOf(listener);
// Removes this instance's listeners and closes the underlying fs_watchFile
// instance if there are no more listeners left.
return () => {
delFromSet(cont, KEY_LISTENERS, listener);
delFromSet(cont, KEY_RAW, rawEmitter);
if (isEmptySet(cont.listeners)) {
FsWatchFileInstances.delete(fullPath);
unwatchFile(fullPath);
cont.options = cont.watcher = undefined;
Object.freeze(cont);
}
};
};
/**
* @mixin
*/
export class NodeFsHandler {
fsw: FSWatcher;
_boundHandleError: (error: unknown) => void;
constructor(fsW: FSWatcher) {
this.fsw = fsW;
this._boundHandleError = (error) => fsW._handleError(error as Error);
}
/**
* Watch file for changes with fs_watchFile or fs_watch.
* @param path to file or dir
* @param listener on fs change
* @returns closer for the watcher instance
*/
_watchWithNodeFs(
path: string,
listener: (path: string, newStats?: any) => void | Promise<void>
): (() => void) | undefined {
const opts = this.fsw.options;
const directory = sp.dirname(path);
const basename = sp.basename(path);
const parent = this.fsw._getWatchedDir(directory);
parent.add(basename);
const absolutePath = sp.resolve(path);
const options: Partial<FSWInstanceOptions> = {
persistent: opts.persistent,
};
if (!listener) listener = EMPTY_FN;
let closer;
if (opts.usePolling) {
const enableBin = opts.interval !== opts.binaryInterval;
options.interval = enableBin && isBinaryPath(basename) ? opts.binaryInterval : opts.interval;
closer = setFsWatchFileListener(path, absolutePath, options, {
listener,
rawEmitter: this.fsw._emitRaw,
});
} else {
closer = setFsWatchListener(path, absolutePath, options, {
listener,
errHandler: this._boundHandleError,
rawEmitter: this.fsw._emitRaw,
});
}
return closer;
}
/**
* Watch a file and emit add event if warranted.
* @returns closer for the watcher instance
*/
_handleFile(file: Path, stats: Stats, initialAdd: boolean): (() => void) | undefined {
if (this.fsw.closed) {
return;
}
const dirname = sp.dirname(file);
const basename = sp.basename(file);
const parent = this.fsw._getWatchedDir(dirname);
// stats is always present
let prevStats = stats;
// if the file is already being watched, do nothing
if (parent.has(basename)) return;
const listener = async (path: Path, newStats: Stats) => {
if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file, 5)) return;
if (!newStats || newStats.mtimeMs === 0) {
try {
const newStats = await stat(file);
if (this.fsw.closed) return;
// Check that change event was not fired because of changed only accessTime.
const at = newStats.atimeMs;
const mt = newStats.mtimeMs;
if (!at || at <= mt || mt !== prevStats.mtimeMs) {
this.fsw._emit(EV.CHANGE, file, newStats);
}
if ((isMacos || isLinux || isFreeBSD) && prevStats.ino !== newStats.ino) {
this.fsw._closeFile(path);
prevStats = newStats;
const closer = this._watchWithNodeFs(file, listener);
if (closer) this.fsw._addPathCloser(path, closer);
} else {
prevStats = newStats;
}
} catch (error) {
// Fix issues where mtime is null but file is still present
this.fsw._remove(dirname, basename);
}
// add is about to be emitted if file not already tracked in parent
} else if (parent.has(basename)) {
// Check that change event was not fired because of changed only accessTime.
const at = newStats.atimeMs;
const mt = newStats.mtimeMs;
if (!at || at <= mt || mt !== prevStats.mtimeMs) {
this.fsw._emit(EV.CHANGE, file, newStats);
}
prevStats = newStats;
}
};
// kick off the watcher
const closer = this._watchWithNodeFs(file, listener);
// emit an add event if we're supposed to
if (!(initialAdd && this.fsw.options.ignoreInitial) && this.fsw._isntIgnored(file)) {
if (!this.fsw._throttle(EV.ADD, file, 0)) return;
this.fsw._emit(EV.ADD, file, stats);
}
return closer;
}
/**
* Handle symlinks encountered while reading a dir.
* @param entry returned by readdirp
* @param directory path of dir being read
* @param path of this item
* @param item basename of this item
* @returns true if no more processing is needed for this entry.
*/
async _handleSymlink(
entry: EntryInfo,
directory: string,
path: Path,
item: string
): Promise<boolean | undefined> {
if (this.fsw.closed) {
return;
}
const full = entry.fullPath;
const dir = this.fsw._getWatchedDir(directory);
if (!this.fsw.options.followSymlinks) {
// watch symlink directly (don't follow) and detect changes
this.fsw._incrReadyCount();
let linkPath;
try {
linkPath = await fsrealpath(path);
} catch (e) {
this.fsw._emitReady();
return true;
}
if (this.fsw.closed) return;
if (dir.has(item)) {
if (this.fsw._symlinkPaths.get(full) !== linkPath) {
this.fsw._symlinkPaths.set(full, linkPath);
this.fsw._emit(EV.CHANGE, path, entry.stats);
}
} else {
dir.add(item);
this.fsw._symlinkPaths.set(full, linkPath);
this.fsw._emit(EV.ADD, path, entry.stats);
}
this.fsw._emitReady();
return true;
}
// don't follow the same symlink more than once
if (this.fsw._symlinkPaths.has(full)) {
return true;
}
this.fsw._symlinkPaths.set(full, true);
}
_handleRead(
directory: string,
initialAdd: boolean,
wh: WatchHelper,
target: Path | undefined,
dir: Path,
depth: number,
throttler: Throttler
): Promise<unknown> | undefined {
// Normalize the directory name on Windows
directory = sp.join(directory, '');
const throttleKey = target ? `${directory}:${target}` : directory;
throttler = this.fsw._throttle('readdir', throttleKey, 1000) as Throttler;
if (!throttler) return;
const previous = this.fsw._getWatchedDir(wh.path);
const current = new Set();
let stream = this.fsw._readdirp(directory, {
fileFilter: (entry: EntryInfo) => wh.filterPath(entry),
directoryFilter: (entry: EntryInfo) => wh.filterDir(entry),
});
if (!stream) return;
stream
.on(STR_DATA, async (entry) => {
if (this.fsw.closed) {
stream = undefined;
return;
}
const item = entry.path;
let path = sp.join(directory, item);
current.add(item);
if (
entry.stats.isSymbolicLink() &&
(await this._handleSymlink(entry, directory, path, item))
) {
return;
}
if (this.fsw.closed) {
stream = undefined;
return;
}
// Files that present in current directory snapshot
// but absent in previous are added to watch list and
// emit `add` event.
if (item === target || (!target && !previous.has(item))) {
this.fsw._incrReadyCount();
// ensure relativeness of path is preserved in case of watcher reuse
path = sp.join(dir, sp.relative(dir, path));
this._addToNodeFs(path, initialAdd, wh, depth + 1);
}
})
.on(EV.ERROR, this._boundHandleError);
return new Promise((resolve, reject) => {
if (!stream) return reject();
stream.once(STR_END, () => {
if (this.fsw.closed) {
stream = undefined;
return;
}
const wasThrottled = throttler ? throttler.clear() : false;
resolve(undefined);
// Files that absent in current directory snapshot
// but present in previous emit `remove` event
// and are removed from @watched[directory].
previous
.getChildren()
.filter((item) => {
return item !== directory && !current.has(item);
})
.forEach((item) => {
this.fsw._remove(directory, item);
});
stream = undefined;
// one more time for any missed in case changes came in extremely quickly
if (wasThrottled) this._handleRead(directory, false, wh, target, dir, depth, throttler);
});
});
}
/**
* Read directory to add / remove files from `@watched` list and re-read it on change.
* @param dir fs path
* @param stats
* @param initialAdd
* @param depth relative to user-supplied path
* @param target child path targeted for watch
* @param wh Common watch helpers for this path
* @param realpath
* @returns closer for the watcher instance.
*/
async _handleDir(
dir: string,
stats: Stats,
initialAdd: boolean,
depth: number,
target: string | undefined,
wh: WatchHelper,
realpath: string
): Promise<(() => void) | undefined> {
const parentDir = this.fsw._getWatchedDir(sp.dirname(dir));
const tracked = parentDir.has(sp.basename(dir));
if (!(initialAdd && this.fsw.options.ignoreInitial) && !target && !tracked) {
this.fsw._emit(EV.ADD_DIR, dir, stats);
}
// ensure dir is tracked (harmless if redundant)
parentDir.add(sp.basename(dir));
this.fsw._getWatchedDir(dir);
let throttler!: Throttler;
let closer;
const oDepth = this.fsw.options.depth;
if ((oDepth == null || depth <= oDepth) && !this.fsw._symlinkPaths.has(realpath)) {
if (!target) {
await this._handleRead(dir, initialAdd, wh, target, dir, depth, throttler);
if (this.fsw.closed) return;
}
closer = this._watchWithNodeFs(dir, (dirPath, stats) => {
// if current directory is removed, do nothing
if (stats && stats.mtimeMs === 0) return;
this._handleRead(dirPath, false, wh, target, dir, depth, throttler);
});
}
return closer;
}
/**
* Handle added file, directory, or glob pattern.
* Delegates call to _handleFile / _handleDir after checks.
* @param path to file or ir
* @param initialAdd was the file added at watch instantiation?
* @param priorWh depth relative to user-supplied path
* @param depth Child path actually targeted for watch
* @param target Child path actually targeted for watch
*/
async _addToNodeFs(
path: string,
initialAdd: boolean,
priorWh: WatchHelper | undefined,
depth: number,
target?: string
): Promise<string | false | undefined> {
const ready = this.fsw._emitReady;
if (this.fsw._isIgnored(path) || this.fsw.closed) {
ready();
return false;
}
const wh = this.fsw._getWatchHelpers(path);
if (priorWh) {
wh.filterPath = (entry) => priorWh.filterPath(entry);
wh.filterDir = (entry) => priorWh.filterDir(entry);
}
// evaluate what is at the path we're being asked to watch
try {
const stats = await statMethods[wh.statMethod](wh.watchPath);
if (this.fsw.closed) return;
if (this.fsw._isIgnored(wh.watchPath, stats)) {
ready();
return false;
}
const follow = this.fsw.options.followSymlinks;
let closer;
if (stats.isDirectory()) {
const absPath = sp.resolve(path);
const targetPath = follow ? await fsrealpath(path) : path;
if (this.fsw.closed) return;
closer = await this._handleDir(
wh.watchPath,
stats,
initialAdd,
depth,
target,
wh,
targetPath
);
if (this.fsw.closed) return;
// preserve this symlink's target path
if (absPath !== targetPath && targetPath !== undefined) {
this.fsw._symlinkPaths.set(absPath, targetPath);
}
} else if (stats.isSymbolicLink()) {
const targetPath = follow ? await fsrealpath(path) : path;
if (this.fsw.closed) return;
const parent = sp.dirname(wh.watchPath);
this.fsw._getWatchedDir(parent).add(wh.watchPath);
this.fsw._emit(EV.ADD, wh.watchPath, stats);
closer = await this._handleDir(parent, stats, initialAdd, depth, path, wh, targetPath);
if (this.fsw.closed) return;
// preserve this symlink's target path
if (targetPath !== undefined) {
this.fsw._symlinkPaths.set(sp.resolve(path), targetPath);
}
} else {
closer = this._handleFile(wh.watchPath, stats, initialAdd);
}
ready();
if (closer) this.fsw._addPathCloser(path, closer);
return false;
} catch (error) {
if (this.fsw._handleError(error as any)) {
ready();
return path;
}
}
}
}
================================================
FILE: src/index.test.ts
================================================
import { afterEach, beforeEach, describe, it } from '@paulmillr/jsbt/test.js';
import { deepEqual, equal, ok, throws } from 'node:assert/strict';
import { exec as cexec } from 'node:child_process';
import {
appendFile,
mkdir as mkd,
readFile as read,
rename,
rm,
symlink,
unlink,
writeFile as write,
} from 'node:fs/promises';
import { tmpdir } from 'node:os';
import * as sp from 'node:path';
import { fileURLToPath, pathToFileURL, URL } from 'node:url';
import { promisify } from 'node:util';
import { type Spy, type SpyFn, spy as createSpy } from 'tinyspy';
import upath from 'upath';
import type { EmitArgs, FSWatcherEventMap } from './index.js';
import { EVENTS as EV, isIBMi, isMacos, isWindows } from './handler.js';
import * as chokidar from './index.js';
const TEST_TIMEOUT = 32000; // ms
const imetaurl = import.meta.url;
const FIXTURES_PATH = sp.join(tmpdir(), 'chokidar-' + time());
const WATCHERS: chokidar.FSWatcher[] = [];
let testId = 0;
let currentDir: string;
let USE_SLOW_DELAY: number | undefined;
function time() {
return Date.now().toString();
}
const exec = promisify(cexec);
function rmr(dir: string) {
return rm(dir, { recursive: true, force: true });
}
function mkdir(dir: string, opts = {}) {
const mode = 0o755; // read + execute
return mkd(dir, { mode: mode, ...opts });
}
function calledWith<TArgs extends unknown[], TReturn>(
spy: Spy<TArgs, TReturn>,
args: TArgs,
strict?: boolean
): boolean {
return getCallsWith(spy, args, strict).length > 0;
}
function getCallsWith<TArgs extends unknown[], TReturn>(
spy: Spy<TArgs, TReturn>,
args: TArgs,
strict?: boolean
): TArgs[] {
return spy.calls.filter(
(call) => (!strict || args.length === call.length) && args.every((arg, i) => call[i] === arg)
);
}
function alwaysCalledWith<TArgs extends unknown[], TReturn>(
spy: Spy<TArgs, TReturn>,
args: TArgs,
strict?: boolean
): boolean {
return spy.calls.every(
(call) => (!strict || args.length === call.length) && args.every((arg, i) => call[i] === arg)
);
}
// spyOnReady
const aspy = (
watcher: chokidar.FSWatcher,
eventName: string,
spy: SpyFn | null = null,
noStat: boolean = false
): Promise<Spy> => {
if (typeof eventName !== 'string') {
throw new TypeError('aspy: eventName must be a String');
}
if (spy == null) spy = createSpy();
return new Promise((resolve, reject) => {
const handler = noStat
? eventName === EV.ALL
? (event: string, path: string) => spy(event, path)
: (path: string) => spy(path)
: spy;
const timeout = setTimeout(() => {
reject(new Error('timeout'));
}, TEST_TIMEOUT);
watcher.on(EV.ERROR, (...args) => {
clearTimeout(timeout);
reject(...args);
});
watcher.on(EV.READY, () => {
clearTimeout(timeout);
resolve(spy);
});
watcher.on(eventName as keyof FSWatcherEventMap, handler);
});
};
const waitForWatcher = (watcher: chokidar.FSWatcher) => {
return new Promise<void>((resolve, reject) => {
const timeout = setTimeout(() => {
reject(new Error('timeout'));
}, TEST_TIMEOUT);
watcher.on(EV.ERROR, (...args) => {
clearTimeout(timeout);
reject(...args);
});
watcher.on(EV.READY, (...args) => {
clearTimeout(timeout);
resolve(...args);
});
});
};
async function delay(delayTime?: number) {
return new Promise<void>((resolve) => {
const timer = delayTime || USE_SLOW_DELAY || 20;
setTimeout(resolve, timer);
});
}
// dir path
function dpath(subPath: string) {
const subd = (testId && testId.toString()) || '';
return sp.join(FIXTURES_PATH, subd, subPath);
}
// glob path
function gpath(subPath: string) {
const subd = (testId && testId.toString()) || '';
return upath.join(FIXTURES_PATH, subd, subPath);
}
currentDir = dpath('');
function cwatch(
path: Parameters<typeof chokidar.watch>[0] = currentDir,
opts?: chokidar.ChokidarOptions
) {
const wt = chokidar.watch(path, opts);
WATCHERS.push(wt);
return wt;
}
function isSpyReady(spy: Spy | [spy: Spy, callCount: number, args?: unknown[]]): boolean {
if (Array.isArray(spy)) {
const [spyFn, callCount, args] = spy;
if (args) {
return getCallsWith(spyFn, args).length >= callCount;
}
return spyFn.callCount >= callCount;
}
return spy.callCount >= 1;
}
function waitFor(spies: Array<Spy | [spy: Spy, callCount: number, args?: unknown[]]>) {
if (spies.length === 0) throw new Error('need at least 1 spy');
// if (spies.length > 1) throw new Error('need 1 spy');
return new Promise<void>((resolve, reject) => {
let checkTimer: ReturnType<typeof setTimeout> = setInterval(() => {
if (!spies.every(isSpyReady)) return;
clearInterval(checkTimer);
clearTimeout(timeout);
resolve();
}, 20);
const timeout = setTimeout(() => {
clearInterval(checkTimer);
reject(new Error('timeout waitFor, passed ms: ' + TEST_TIMEOUT));
}, TEST_TIMEOUT);
});
}
function waitForEvents(watcher: chokidar.FSWatcher, count: number) {
return new Promise<string[]>((resolve, reject) => {
const timeout = setTimeout(() => {
reject(new Error('timeout waitForEvents, passed ms: ' + TEST_TIMEOUT));
}, TEST_TIMEOUT);
const events: string[] = [];
const handler = (event: string, path: string) => {
events.push(`[ALL] ${event}: ${path}`);
if (events.length === count) {
watcher.off('all', handler);
clearTimeout(timeout);
resolve(events);
}
};
watcher.on('all', handler);
});
}
const runTests = (baseopts: chokidar.ChokidarOptions) => {
let macosFswatch = isMacos && !baseopts.usePolling;
let options: chokidar.ChokidarOptions;
USE_SLOW_DELAY = macosFswatch ? 100 : undefined;
baseopts.persistent = true;
beforeEach(function clean() {
options = {};
Object.keys(baseopts).forEach((key) => {
(options as Record<PropertyKey, unknown>)[key] =
baseopts[key as keyof chokidar.ChokidarOptions];
});
});
describe('watch a directory', () => {
let readySpy: SpyFn<[], void>;
let rawSpy: SpyFn<FSWatcherEventMap['raw'], void>;
let watcher: chokidar.FSWatcher;
let watcher2: chokidar.FSWatcher;
beforeEach(async () => {
options.ignoreInitial = true;
options.alwaysStat = true;
readySpy = createSpy<[], void>(function readySpy() {});
rawSpy = createSpy<FSWatcherEventMap['raw'], void>(function rawSpy() {});
watcher = cwatch(currentDir, options).on(EV.READY, readySpy).on(EV.RAW, rawSpy);
await waitForWatcher(watcher);
});
afterEach(async () => {
await waitFor([readySpy]);
await watcher.close();
equal(readySpy.callCount, 1);
});
it('should produce an instance of chokidar.FSWatcher', () => {
ok(watcher instanceof chokidar.FSWatcher);
});
it('should expose public API methods', () => {
ok(typeof watcher.on === 'function');
ok(typeof watcher.emit === 'function');
ok(typeof watcher.add === 'function');
ok(typeof watcher.close === 'function');
ok(typeof watcher.getWatched === 'function');
});
it('should emit `add` event when file was added', async () => {
const testPath = dpath('add.txt');
const spy = createSpy<EmitArgs, void>(function addSpy() {});
watcher.on(EV.ADD, spy);
await delay();
await write(testPath, time());
await waitFor([spy]);
equal(spy.callCount, 1);
ok(calledWith(spy, [testPath]));
ok(spy.calls[0][1]); // stats
ok(rawSpy.called);
});
it('should emit nine `add` events when nine files were added in one directory', async () => {
const paths: string[] = [];
for (let i = 1; i <= 9; i++) {
paths.push(dpath(`add${i}.txt`));
}
const spy = createSpy();
watcher.on(EV.ADD, (path) => {
spy(path);
});
await write(paths[0], time());
await write(paths[1], time());
await write(paths[2], time());
await write(paths[3], time());
await write(paths[4], time());
await delay(100);
await write(paths[5], time());
await write(paths[6], time());
await delay(150);
await write(paths[7], time());
await write(paths[8], time());
await waitFor([[spy, 4]]);
await delay(1000);
await waitFor([[spy, 9]]);
paths.forEach((path) => {
ok(calledWith(spy, [path]));
});
});
it('should emit thirtythree `add` events when thirtythree files were added in nine directories', async () => {
await watcher.close();
const test1Path = dpath('add1.txt');
const testb1Path = dpath('b/add1.txt');
const testc1Path = dpath('c/add1.txt');
const testd1Path = dpath('d/add1.txt');
const teste1Path = dpath('e/add1.txt');
const testf1Path = dpath('f/add1.txt');
const testg1Path = dpath('g/add1.txt');
const testh1Path = dpath('h/add1.txt');
const testi1Path = dpath('i/add1.txt');
const test2Path = dpath('add2.txt');
const testb2Path = dpath('b/add2.txt');
const testc2Path = dpath('c/add2.txt');
const test3Path = dpath('add3.txt');
const testb3Path = dpath('b/add3.txt');
const testc3Path = dpath('c/add3.txt');
const test4Path = dpath('add4.txt');
const testb4Path = dpath('b/add4.txt');
const testc4Path = dpath('c/add4.txt');
const test5Path = dpath('add5.txt');
const testb5Path = dpath('b/add5.txt');
const testc5Path = dpath('c/add5.txt');
const test6Path = dpath('add6.txt');
const testb6Path = dpath('b/add6.txt');
const testc6Path = dpath('c/add6.txt');
const test7Path = dpath('add7.txt');
const testb7Path = dpath('b/add7.txt');
const testc7Path = dpath('c/add7.txt');
const test8Path = dpath('add8.txt');
const testb8Path = dpath('b/add8.txt');
const testc8Path = dpath('c/add8.txt');
const test9Path = dpath('add9.txt');
const testb9Path = dpath('b/add9.txt');
const testc9Path = dpath('c/add9.txt');
await mkdir(dpath('b'));
await mkdir(dpath('c'));
await mkdir(dpath('d'));
await mkdir(dpath('e'));
await mkdir(dpath('f'));
await mkdir(dpath('g'));
await mkdir(dpath('h'));
await mkdir(dpath('i'));
await delay();
readySpy.reset();
watcher2 = cwatch(currentDir, options).on(EV.READY, readySpy).on(EV.RAW, rawSpy);
const spy = await aspy(watcher2, EV.ADD, null, true);
const filesToWrite = [
test1Path,
test2Path,
test3Path,
test4Path,
test5Path,
test6Path,
test7Path,
test8Path,
test9Path,
testb1Path,
testb2Path,
testb3Path,
testb4Path,
testb5Path,
testb6Path,
testb7Path,
testb8Path,
testb9Path,
testc1Path,
testc2Path,
testc3Path,
testc4Path,
testc5Path,
testc6Path,
testc7Path,
testc8Path,
testc9Path,
testd1Path,
teste1Path,
testf1Path,
testg1Path,
testh1Path,
testi1Path,
];
let currentCallCount = 0;
for (const fileToWrite of filesToWrite) {
await write(fileToWrite, time());
await waitFor([[spy, ++currentCallCount]]);
}
ok(calledWith(spy, [test1Path]));
ok(calledWith(spy, [test2Path]));
ok(calledWith(spy, [test3Path]));
ok(calledWith(spy, [test4Path]));
ok(calledWith(spy, [test5Path]));
ok(calledWith(spy, [test6Path]));
ok(calledWith(spy, [test7Path]));
ok(calledWith(spy, [test8Path]));
ok(calledWith(spy, [test9Path]));
ok(calledWith(spy, [testb1Path]));
ok(calledWith(spy, [testb2Path]));
ok(calledWith(spy, [testb3Path]));
ok(calledWith(spy, [testb4Path]));
ok(calledWith(spy, [testb5Path]));
ok(calledWith(spy, [testb6Path]));
ok(calledWith(spy, [testb7Path]));
ok(calledWith(spy, [testb8Path]));
ok(calledWith(spy, [testb9Path]));
ok(calledWith(spy, [testc1Path]));
ok(calledWith(spy, [testc2Path]));
ok(calledWith(spy, [testc3Path]));
ok(calledWith(spy, [testc4Path]));
ok(calledWith(spy, [testc5Path]));
ok(calledWith(spy, [testc6Path]));
ok(calledWith(spy, [testc7Path]));
ok(calledWith(spy, [testc8Path]));
ok(calledWith(spy, [testc9Path]));
ok(calledWith(spy, [testd1Path]));
ok(calledWith(spy, [teste1Path]));
ok(calledWith(spy, [testf1Path]));
ok(calledWith(spy, [testg1Path]));
ok(calledWith(spy, [testh1Path]));
ok(calledWith(spy, [testi1Path]));
});
it('should emit `addDir` event when directory was added', async () => {
const testDir = dpath('subdir');
const spy = createSpy<EmitArgs, void>(function addDirSpy() {});
watcher.on(EV.ADD_DIR, spy);
equal(spy.called, false);
await mkdir(testDir);
await waitFor([spy]);
equal(spy.callCount, 1);
ok(calledWith(spy, [testDir]));
ok(spy.calls[0][1]); // stats
ok(rawSpy.called);
});
it('should emit `change` event when file was changed', async () => {
const testPath = dpath('change.txt');
const spy = createSpy<EmitArgs, void>(function changeSpy() {});
watcher.on(EV.CHANGE, spy);
equal(spy.called, false);
await write(testPath, time());
await waitFor([spy]);
ok(calledWith(spy, [testPath]));
ok(spy.calls[0][1]); // stats
ok(rawSpy.called);
equal(spy.callCount, 1);
});
it('should emit `unlink` event when file was removed', async () => {
const testPath = dpath('unlink.txt');
const spy = createSpy<EmitArgs, void>(function unlinkSpy() {});
watcher.on(EV.UNLINK, spy);
equal(spy.called, false);
await unlink(testPath);
await waitFor([spy]);
ok(calledWith(spy, [testPath]));
equal(!spy.calls[0][1], true); // no stats
ok(rawSpy.called);
equal(spy.callCount, 1);
});
it('should emit `unlinkDir` event when a directory was removed', async () => {
const testDir = dpath('subdir');
const spy = createSpy<EmitArgs, void>(function unlinkDirSpy() {});
await mkdir(testDir);
await delay(300);
watcher.on(EV.UNLINK_DIR, spy);
await rmr(testDir);
await waitFor([spy]);
ok(calledWith(spy, [testDir]));
equal(!spy.calls[0][1], true); // no stats
ok(rawSpy.called);
equal(spy.callCount, 1);
});
it('should emit two `unlinkDir` event when two nested directories were removed', async () => {
const testDir = dpath('subdir');
const testDir2 = dpath('subdir/subdir2');
const testDir3 = dpath('subdir/subdir2/subdir3');
const spy = createSpy<EmitArgs, void>(function unlinkDirSpy() {});
await mkdir(testDir);
await mkdir(testDir2);
await mkdir(testDir3);
await delay(300);
watcher.on(EV.UNLINK_DIR, spy);
await rmr(testDir2);
await waitFor([[spy, 2]]);
ok(calledWith(spy, [testDir2]));
ok(calledWith(spy, [testDir3]));
equal(!spy.calls[0][1], true); // no stats
ok(rawSpy.called);
equal(spy.callCount, 2);
});
it('should emit `unlink` and `add` events when a file is renamed', async () => {
const unlinkSpy = createSpy<EmitArgs, void>(function unlink() {});
const addSpy = createSpy<EmitArgs, void>(function add() {});
const testPath = dpath('change.txt');
const newPath = dpath('moved.txt');
watcher.on(EV.UNLINK, unlinkSpy).on(EV.ADD, addSpy);
equal(unlinkSpy.called, false);
equal(addSpy.called, false);
await delay();
await rename(testPath, newPath);
await waitFor([unlinkSpy, addSpy]);
ok(calledWith(unlinkSpy, [testPath]));
equal(!unlinkSpy.calls[0][1], true); // no stats
equal(addSpy.callCount, 1);
ok(calledWith(addSpy, [newPath]));
ok(addSpy.calls[0][1]); // stats
ok(rawSpy.called);
if (!macosFswatch) equal(unlinkSpy.callCount, 1);
});
it('should emit `add`, not `change`, when previously deleted file is re-added', async () => {
if (isWindows) {
console.warn('test skipped');
return true;
}
const unlinkSpy = createSpy<EmitArgs, void>(function unlink() {});
const addSpy = createSpy<EmitArgs, void>(function add() {});
const changeSpy = createSpy<EmitArgs, void>(function change() {});
const testPath = dpath('add.txt');
watcher.on(EV.UNLINK, unlinkSpy).on(EV.ADD, addSpy).on(EV.CHANGE, changeSpy);
await write(testPath, 'hello');
await waitFor([[addSpy, 1, [testPath]]]);
equal(unlinkSpy.called, false);
equal(changeSpy.called, false);
await unlink(testPath);
await waitFor([[unlinkSpy, 1, [testPath]]]);
ok(calledWith(unlinkSpy, [testPath]));
await delay(100);
await write(testPath, time());
await waitFor([[addSpy, 2, [testPath]]]);
ok(calledWith(addSpy, [testPath]));
equal(changeSpy.called, false);
equal(addSpy.callCount, 2);
});
it('should not emit `unlink` for previously moved files', async () => {
const unlinkSpy = createSpy<EmitArgs, void>(function unlink() {});
const testPath = dpath('change.txt');
const newPath1 = dpath('moved.txt');
const newPath2 = dpath('moved-again.txt');
watcher.on(EV.UNLINK, unlinkSpy);
await rename(testPath, newPath1);
await delay(300);
await rename(newPath1, newPath2);
await waitFor([[unlinkSpy, 1, [newPath1]]]);
equal(getCallsWith(unlinkSpy, [testPath]).length, 1);
equal(getCallsWith(unlinkSpy, [newPath1]).length, 1);
equal(getCallsWith(unlinkSpy, [newPath2]).length, 0);
});
it('should survive ENOENT for missing subdirectories', async () => {
const testDir = dpath('notadir');
watcher.add(testDir);
});
it('should notice when a file appears in a new directory', async () => {
const testDir = dpath('subdir');
const testPath = dpath('subdir/add.txt');
const spy = createSpy<EmitArgs, void>(function addSpy() {});
watcher.on(EV.ADD, spy);
equal(spy.called, false);
await mkdir(testDir);
await write(testPath, time());
await waitFor([spy]);
equal(spy.callCount, 1);
ok(calledWith(spy, [testPath]));
ok(spy.calls[0][1]); // stats
ok(rawSpy.called);
});
it('should watch removed and re-added directories', async () => {
const unlinkSpy = createSpy<EmitArgs, void>(function unlinkSpy() {});
const addSpy = createSpy<EmitArgs, void>(function addSpy() {});
const parentPath = dpath('subdir2');
const subPath = dpath('subdir2/subsub');
watcher.on(EV.UNLINK_DIR, unlinkSpy).on(EV.ADD_DIR, addSpy);
await mkdir(parentPath);
await waitFor([[addSpy, 1, [parentPath]]]);
await rmr(parentPath);
await waitFor([[unlinkSpy, 1, [parentPath]]]);
ok(calledWith(unlinkSpy, [parentPath]));
await mkdir(parentPath);
await waitFor([[addSpy, 2]]);
await mkdir(subPath);
await waitFor([[addSpy, 3]]);
ok(calledWith(addSpy, [parentPath]));
ok(calledWith(addSpy, [subPath]));
});
it('should emit `unlinkDir` and `add` when dir is replaced by file', async () => {
options.ignoreInitial = true;
const unlinkSpy = createSpy<EmitArgs, void>(function unlinkSpy() {});
const addSpy = createSpy<EmitArgs, void>(function addSpy() {});
const testPath = dpath('dirFile');
await mkdir(testPath);
await delay(300);
watcher.on(EV.UNLINK_DIR, unlinkSpy).on(EV.ADD, addSpy);
await rmr(testPath);
await waitFor([unlinkSpy]);
await write(testPath, 'file content');
await waitFor([addSpy]);
ok(calledWith(unlinkSpy, [testPath]));
ok(calledWith(addSpy, [testPath]));
});
it('should emit `unlink` and `addDir` when file is replaced by dir', async () => {
options.ignoreInitial = true;
const unlinkSpy = createSpy<EmitArgs, void>(function unlinkSpy() {});
const addSpy = createSpy<EmitArgs, void>(function addSpy() {});
const testPath = dpath('fileDir');
await write(testPath, 'file content');
watcher.on(EV.UNLINK, unlinkSpy).on(EV.ADD_DIR, addSpy);
await delay(300);
await unlink(testPath);
await delay(300);
await mkdir(testPath);
await waitFor([addSpy, unlinkSpy]);
ok(calledWith(unlinkSpy, [testPath]));
ok(calledWith(addSpy, [testPath]));
});
});
describe('watch individual files', () => {
it('should emit `ready` when three files were added', async () => {
const readySpy = createSpy(function readySpy() {});
const watcher = cwatch(currentDir, options).on(EV.READY, readySpy);
const path1 = dpath('add1.txt');
const path2 = dpath('add2.txt');
const path3 = dpath('add3.txt');
watcher.add(path1);
watcher.add(path2);
watcher.add(path3);
await waitForWatcher(watcher);
// callCount is 1 on macOS, 4 on Ubuntu
ok(readySpy.callCount >= 1);
});
it('should detect changes', async () => {
const testPath = dpath('change.txt');
const watcher = cwatch(testPath, options);
const spy = await aspy(watcher, EV.CHANGE);
await write(testPath, time());
await waitFor([spy]);
ok(alwaysCalledWith(spy, [testPath]));
});
it('should detect unlinks', async () => {
const testPath = dpath('unlink.txt');
const watcher = cwatch(testPath, options);
const spy = await aspy(watcher, EV.UNLINK);
await delay();
await unlink(testPath);
await waitFor([spy]);
ok(calledWith(spy, [testPath]));
});
it('should detect unlink and re-add', async () => {
options.ignoreInitial = true;
const unlinkSpy = createSpy<EmitArgs, void>(function unlinkSpy() {});
const addSpy = createSpy<EmitArgs, void>(function addSpy() {});
const testPath = dpath('unlink.txt');
const watcher = cwatch([testPath], options).on(EV.UNLINK, unlinkSpy).on(EV.ADD, addSpy);
await waitForWatcher(watcher);
await delay();
await unlink(testPath);
await waitFor([unlinkSpy]);
ok(calledWith(unlinkSpy, [testPath]));
await delay();
await write(testPath, 're-added');
await waitFor([addSpy]);
ok(calledWith(addSpy, [testPath]));
});
it('should ignore unwatched siblings', async () => {
const testPath = dpath('add.txt');
const siblingPath = dpath('change.txt');
const watcher = cwatch(testPath, options);
const spy = await aspy(watcher, EV.ALL);
await delay();
await write(siblingPath, time());
await write(testPath, time());
await waitFor([spy]);
ok(alwaysCalledWith(spy, [EV.ADD, testPath]));
});
it('should detect safe-edit', async () => {
const testPath = dpath('change.txt');
const safePath = dpath('tmp.txt');
await write(testPath, time());
const watcher = cwatch(testPath, options);
const spy = await aspy(watcher, EV.ALL);
await delay();
await write(safePath, time());
await rename(safePath, testPath);
await delay(300);
await write(safePath, time());
await rename(safePath, testPath);
await delay(300);
await write(safePath, time());
await rename(safePath, testPath);
await delay(300);
await waitFor([spy]);
equal(getCallsWith(spy, [EV.CHANGE, testPath]).length, 3);
});
// PR 682 is failing.
describe.skip('Skipping gh-682: should detect unlink', () => {
it('should detect unlink while watching a non-existent second file in another directory', async () => {
const testPath = dpath('unlink.txt');
const otherDirPath = dpath('other-dir');
const otherPath = dpath('other-dir/other.txt');
await mkdir(otherDirPath);
const watcher = cwatch([testPath, otherPath], options);
// intentionally for this test don't write write(otherPath, 'other');
const spy = await aspy(watcher, EV.UNLINK);
await delay();
await unlink(testPath);
await waitFor([spy]);
ok(calledWith(spy, [testPath]));
});
it('should detect unlink and re-add while watching a second file', async () => {
options.ignoreInitial = true;
const unlinkSpy = createSpy<EmitArgs, void>(function unlinkSpy() {});
const addSpy = createSpy<EmitArgs, void>(function addSpy() {});
const testPath = dpath('unlink.txt');
const otherPath = dpath('other.txt');
await write(otherPath, 'other');
const watcher = cwatch([testPath, otherPath], options)
.on(EV.UNLINK, unlinkSpy)
.on(EV.ADD, addSpy);
await waitForWatcher(watcher);
await delay();
await unlink(testPath);
await waitFor([unlinkSpy]);
await delay();
ok(calledWith(unlinkSpy, [testPath]));
await delay();
await write(testPath, 're-added');
await waitFor([addSpy]);
ok(calledWith(addSpy, [testPath]));
});
it('should detect unlink and re-add while watching a non-existent second file in another directory', async () => {
options.ignoreInitial = true;
const unlinkSpy = createSpy<EmitArgs, void>(function unlinkSpy() {});
const addSpy = createSpy<EmitArgs, void>(function addSpy() {});
const testPath = dpath('unlink.txt');
const otherDirPath = dpath('other-dir');
const otherPath = dpath('other-dir/other.txt');
await mkdir(otherDirPath);
// intentionally for this test don't write write(otherPath, 'other');
const watcher = cwatch([testPath, otherPath], options)
.on(EV.UNLINK, unlinkSpy)
.on(EV.ADD, addSpy);
await waitForWatcher(watcher);
await delay();
await unlink(testPath);
await waitFor([unlinkSpy]);
await delay();
ok(calledWith(unlinkSpy, [testPath]));
await delay();
await write(testPath, 're-added');
await waitFor([addSpy]);
ok(calledWith(addSpy, [testPath]));
});
it('should detect unlink and re-add while watching a non-existent second file in the same directory', async () => {
options.ignoreInitial = true;
const unlinkSpy = createSpy<EmitArgs, void>(function unlinkSpy() {});
const addSpy = createSpy<EmitArgs, void>(function addSpy() {});
const testPath = dpath('unlink.txt');
const otherPath = dpath('other.txt');
// intentionally for this test don't write write(otherPath, 'other');
const watcher = cwatch([testPath, otherPath], options)
.on(EV.UNLINK, unlinkSpy)
.on(EV.ADD, addSpy);
await waitForWatcher(watcher);
await delay();
await unlink(testPath);
await waitFor([unlinkSpy]);
await delay();
ok(calledWith(unlinkSpy, [testPath]));
await delay();
await write(testPath, 're-added');
await waitFor([addSpy]);
ok(calledWith(addSpy, [testPath]));
});
it('should detect two unlinks and one re-add', async () => {
options.ignoreInitial = true;
const unlinkSpy = createSpy<EmitArgs, void>(function unlinkSpy() {});
const addSpy = createSpy<EmitArgs, void>(function addSpy() {});
const testPath = dpath('unlink.txt');
const otherPath = dpath('other.txt');
await write(otherPath, 'other');
const watcher = cwatch([testPath, otherPath], options)
.on(EV.UNLINK, unlinkSpy)
.on(EV.ADD, addSpy);
await waitForWatcher(watcher);
await delay();
await unlink(otherPath);
await delay();
await unlink(testPath);
await waitFor([[unlinkSpy, 2]]);
await delay();
ok(calledWith(unlinkSpy, [otherPath]));
ok(calledWith(unlinkSpy, [testPath]));
await delay();
await write(testPath, 're-added');
await waitFor([addSpy]);
ok(calledWith(addSpy, [testPath]));
});
it('should detect unlink and re-add while watching a second file and a non-existent third file', async () => {
options.ignoreInitial = true;
const unlinkSpy = createSpy<EmitArgs, void>(function unlinkSpy() {});
const addSpy = createSpy<EmitArgs, void>(function addSpy() {});
const testPath = dpath('unlink.txt');
const otherPath = dpath('other.txt');
const other2Path = dpath('other2.txt');
await write(otherPath, 'other');
// intentionally for this test don't write write(other2Path, 'other2');
const watcher = cwatch([testPath, otherPath, other2Path], options)
.on(EV.UNLINK, unlinkSpy)
.on(EV.ADD, addSpy);
await waitForWatcher(watcher);
await delay();
await unlink(testPath);
await waitFor([unlinkSpy]);
await delay();
ok(calledWith(unlinkSpy, [testPath]));
await delay();
await write(testPath, 're-added');
await waitFor([addSpy]);
ok(calledWith(addSpy, [testPath]));
});
});
});
describe('renamed directory', () => {
it('should emit `add` for a file in a renamed directory', async () => {
options.ignoreInitial = true;
const testDir = dpath('subdir');
const testPath = dpath('subdir/add.txt');
const renamedDir = dpath('subdir-renamed');
const expectedPath = sp.join(renamedDir, 'add.txt');
await mkdir(testDir);
await write(testPath, time());
const watcher = cwatch(currentDir, options);
const spy = await aspy(watcher, EV.ADD);
await delay(1000);
await rename(testDir, renamedDir);
await waitFor([[spy, 1, [expectedPath]]]);
ok(calledWith(spy, [expectedPath]));
});
});
describe('watch non-existent paths', () => {
it('should watch non-existent file and detect add', async () => {
const testPath = dpath('add.txt');
const watcher = cwatch(testPath, options);
const spy = await aspy(watcher, EV.ADD);
await delay();
await write(testPath, time());
await waitFor([spy]);
ok(calledWith(spy, [testPath]));
});
it('should watch non-existent dir and detect addDir/add', async () => {
const testDir = dpath('subdir');
const testPath = dpath('subdir/add.txt');
const watcher = cwatch(testDir, options);
const spy = await aspy(watcher, EV.ALL);
equal(spy.called, false);
await delay();
await mkdir(testDir);
await waitFor([[spy, 1, [EV.ADD_DIR]]]);
await write(testPath, 'hello');
await waitFor([[spy, 1, [EV.ADD]]]);
ok(calledWith(spy, [EV.ADD_DIR, testDir]));
ok(calledWith(spy, [EV.ADD, testPath]));
});
});
describe('not watch glob patterns', () => {
it('should not confuse glob-like filenames with globs', async () => {
const filePath = dpath('nota[glob].txt');
await write(filePath, 'b');
await delay();
const spy = await aspy(cwatch(currentDir, options), EV.ALL);
ok(calledWith(spy, [EV.ADD, filePath]));
await delay();
await write(filePath, time());
await waitFor([[spy, 1, [EV.CHANGE, filePath]]]);
ok(calledWith(spy, [EV.CHANGE, filePath]));
});
it('should treat glob-like directory names as literal directory names when globbing is disabled', async () => {
const filePath = dpath('nota[glob]/a.txt');
const watchPath = dpath('nota[glob]');
const testDir = dpath('nota[glob]');
const matchingDir = dpath('notag');
const matchingFile = dpath('notag/b.txt');
const matchingFile2 = dpath('notal');
await mkdir(testDir);
await write(filePath, 'b');
await mkdir(matchingDir);
await write(matchingFile, 'c');
await write(matchingFile2, 'd');
const watcher = cwatch(watchPath, options);
const spy = await aspy(watcher, EV.ALL);
ok(calledWith(spy, [EV.ADD, filePath]));
equal(calledWith(spy, [EV.ADD_DIR, matchingDir]), false);
equal(calledWith(spy, [EV.ADD, matchingFile]), false);
equal(calledWith(spy, [EV.ADD, matchingFile2]), false);
await delay();
await write(filePath, time());
await waitFor([[spy, 1, [EV.CHANGE, filePath]]]);
ok(calledWith(spy, [EV.CHANGE, filePath]));
});
it('should treat glob-like filenames as literal filenames', async () => {
const filePath = dpath('nota[glob]');
// This isn't using getGlobPath because it isn't treated as a glob
const watchPath = dpath('nota[glob]');
const matchingDir = dpath('notag');
const matchingFile = dpath('notag/a.txt');
const matchingFile2 = dpath('notal');
await write(filePath, 'b');
await mkdir(matchingDir);
await write(matchingFile, 'c');
await write(matchingFile2, 'd');
const watcher = cwatch(watchPath, options);
const spy = await aspy(watcher, EV.ALL);
ok(calledWith(spy, [EV.ADD, filePath]));
equal(calledWith(spy, [EV.ADD_DIR, matchingDir]), false);
equal(calledWith(spy, [EV.ADD, matchingFile]), false);
equal(calledWith(spy, [EV.ADD, matchingFile2]), false);
await delay();
await write(filePath, time());
await waitFor([[spy, 1, [EV.CHANGE, filePath]]]);
ok(calledWith(spy, [EV.CHANGE, filePath]));
});
});
describe('watch symlinks', () => {
if (isWindows) return true;
let linkedDir: string;
beforeEach(async () => {
linkedDir = sp.resolve(currentDir, '..', `${testId}-link`);
await symlink(currentDir, linkedDir, isWindows ? 'dir' : undefined);
await mkdir(dpath('subdir'));
await write(dpath('subdir/add.txt'), 'b');
});
afterEach(async () => {
await unlink(linkedDir);
});
it('should watch symlinked dirs', async () => {
const dirSpy = createSpy<EmitArgs, void>(function dirSpy() {});
const addSpy = createSpy<EmitArgs, void>(function addSpy() {});
const watcher = cwatch(linkedDir, options).on(EV.ADD_DIR, dirSpy).on(EV.ADD, addSpy);
await waitForWatcher(watcher);
ok(calledWith(dirSpy, [linkedDir]));
ok(calledWith(addSpy, [sp.join(linkedDir, 'change.txt')]));
ok(calledWith(addSpy, [sp.join(linkedDir, 'unlink.txt')]));
});
it('should watch symlinked files', async () => {
const changePath = dpath('change.txt');
const linkPath = dpath('link.txt');
await symlink(changePath, linkPath);
const watcher = cwatch(linkPath, options);
const spy = await aspy(watcher, EV.ALL);
await write(changePath, time());
await waitFor([[spy, 1, [EV.CHANGE]]]);
ok(calledWith(spy, [EV.ADD, linkPath]));
ok(calledWith(spy, [EV.CHANGE, linkPath]));
});
it('should follow symlinked files within a normal dir', async () => {
const changePath = dpath('change.txt');
const linkPath = dpath('subdir/link.txt');
await symlink(changePath, linkPath);
const watcher = cwatch(dpath('subdir'), options);
const spy = await aspy(watcher, EV.ALL);
await write(changePath, time());
await waitFor([[spy, 1, [EV.CHANGE, linkPath]]]);
ok(calledWith(spy, [EV.ADD, linkPath]));
ok(calledWith(spy, [EV.CHANGE, linkPath]));
});
it('should watch paths with a symlinked parent', async () => {
const testDir = sp.join(linkedDir, 'subdir');
const testFile = sp.join(testDir, 'add.txt');
const watcher = cwatch(testDir, options);
const spy = await aspy(watcher, EV.ALL);
ok(calledWith(spy, [EV.ADD_DIR, testDir]));
ok(calledWith(spy, [EV.ADD, testFile]));
await write(dpath('subdir/add.txt'), time());
await waitFor([[spy, 1, [EV.CHANGE]]]);
ok(calledWith(spy, [EV.CHANGE, testFile]));
});
it('should not recurse indefinitely on circular symlinks', async () => {
await symlink(currentDir, dpath('subdir/circular'), isWindows ? 'dir' : undefined);
await new Promise<void>((resolve, reject) => {
const watcher = cwatch(currentDir, options);
watcher.on(EV.ERROR, () => {
resolve();
});
watcher.on(EV.READY, () => {
reject('The watcher becomes ready, although he watches a circular symlink.');
});
});
});
it('should recognize changes following symlinked dirs', async () => {
const linkedFilePath = sp.join(linkedDir, 'change.txt');
const watcher = cwatch(linkedDir, options);
const spy = await aspy(watcher, EV.CHANGE);
await write(dpath('change.txt'), time());
await waitFor([[spy, 1, [linkedFilePath]]]);
ok(calledWith(spy, [linkedFilePath]));
});
it('should follow newly created symlinks', async () => {
options.ignoreInitial = true;
const watcher = cwatch(currentDir, options);
const spy = await aspy(watcher, EV.ALL);
await delay();
await symlink(dpath('subdir'), dpath('link'), isWindows ? 'dir' : undefined);
await waitFor([
[spy, 1, [EV.ADD, dpath('link/add.txt')]],
[spy, 1, [EV.ADD_DIR, dpath('link')]],
]);
ok(calledWith(spy, [EV.ADD_DIR, dpath('link')]));
ok(calledWith(spy, [EV.ADD, dpath('link/add.txt')]));
});
it('should watch symlinks as files when followSymlinks:false', async () => {
options.followSymlinks = false;
const watcher = cwatch(linkedDir, options);
const spy = await aspy(watcher, EV.ALL);
equal(calledWith(spy, [EV.ADD_DIR]), false);
ok(calledWith(spy, [EV.ADD, linkedDir]));
equal(spy.callCount, 1);
});
it('should survive ENOENT for missing symlinks when followSymlinks:false', async () => {
options.followSymlinks = false;
const targetDir = dpath('subdir/nonexistent');
await mkdir(targetDir);
await symlink(targetDir, dpath('subdir/broken'), isWindows ? 'dir' : undefined);
await rmr(targetDir);
await delay();
const watcher = cwatch(dpath('subdir'), options);
const spy = await aspy(watcher, EV.ALL);
equal(spy.callCount, 2);
ok(calledWith(spy, [EV.ADD_DIR, dpath('subdir')]));
ok(calledWith(spy, [EV.ADD, dpath('subdir/add.txt')]));
});
it('should watch symlinks within a watched dir as files when followSymlinks:false', async () => {
options.followSymlinks = false;
// Create symlink in linkPath
const linkPath = dpath('link');
await symlink(dpath('subdir'), linkPath);
const spy = await aspy(cwatch(currentDir, options), EV.ALL);
await delay(300);
setTimeout(
async () => {
await write(dpath('subdir/add.txt'), time());
await unlink(linkPath);
await symlink(dpath('subdir/add.txt'), linkPath);
},
options.usePolling ? 1200 : 300
);
await delay(300);
await waitFor([[spy, 1, [EV.CHANGE, linkPath]]]);
equal(calledWith(spy, [EV.ADD_DIR, linkPath]), false);
equal(calledWith(spy, [EV.ADD, dpath('link/add.txt')]), false);
ok(calledWith(spy, [EV.ADD, linkPath]));
ok(calledWith(spy, [EV.CHANGE, linkPath]));
});
it('should not reuse watcher when following a symlink to elsewhere', async () => {
const linkedPath = dpath('outside');
const linkedFilePath = sp.join(linkedPath, 'text.txt');
const linkPath = dpath('subdir/subsub');
await mkdir(linkedPath);
await write(linkedFilePath, 'b');
await symlink(linkedPath, linkPath);
const watcher2 = cwatch(dpath('subdir'), options);
await waitForWatcher(watcher2);
await delay(options.usePolling ? 900 : undefined);
const watchedPath = dpath('subdir/subsub/text.txt');
const watcher = cwatch(watchedPath, options);
const spy = await aspy(watcher, EV.ALL);
await delay();
await write(linkedFilePath, time());
await waitFor([[spy, 1, [EV.CHANGE]]]);
ok(calledWith(spy, [EV.CHANGE, watchedPath]));
});
it('should emit ready event even when broken symlinks are encountered', async () => {
const targetDir = dpath('subdir/nonexistent');
await mkdir(targetDir);
await symlink(targetDir, dpath('subdir/broken'), isWindows ? 'dir' : undefined);
await rmr(targetDir);
const readySpy = createSpy(function readySpy() {});
const watcher = cwatch(dpath('subdir'), options).on(EV.READY, readySpy);
await waitForWatcher(watcher);
equal(readySpy.callCount, 1);
});
});
describe('watch arrays of paths/globs', () => {
it('should watch all paths in an array', async () => {
const testPath = dpath('change.txt');
const testDir = dpath('subdir');
await mkdir(testDir);
const watcher = cwatch([testDir, testPath], options);
const spy = await aspy(watcher, EV.ALL);
ok(calledWith(spy, [EV.ADD, testPath]));
ok(calledWith(spy, [EV.ADD_DIR, testDir]));
equal(calledWith(spy, [EV.ADD, dpath('unlink.txt')]), false);
await write(testPath, time());
await waitFor([[spy, 1, [EV.CHANGE]]]);
ok(calledWith(spy, [EV.CHANGE, testPath]));
});
it('should accommodate nested arrays in input', async () => {
const testPath = dpath('change.txt');
const testDir = dpath('subdir');
await mkdir(testDir);
const watcher = cwatch([[testDir], [testPath]] as unknown as string[], options);
const spy = await aspy(watcher, EV.ALL);
ok(calledWith(spy, [EV.ADD, testPath]));
ok(calledWith(spy, [EV.ADD_DIR, testDir]));
equal(calledWith(spy, [EV.ADD, dpath('unlink.txt')]), false);
await write(testPath, time());
await waitFor([[spy, 1, [EV.CHANGE]]]);
ok(calledWith(spy, [EV.CHANGE, testPath]));
});
it('should throw if provided any non-string paths', () => {
throws(cwatch.bind(null, [[currentDir], /notastring/] as unknown as string[], options), {
name: /^TypeError$/,
message: /non-string/i,
});
});
});
describe('watch options', () => {
describe('ignoreInitial', () => {
describe('false', () => {
beforeEach(() => {
options.ignoreInitial = false;
});
it('should emit `add` events for preexisting files', async () => {
const watcher = cwatch(currentDir, options);
const spy = await aspy(watcher, EV.ADD);
equal(spy.callCount, 2);
});
it('should emit `addDir` event for watched dir', async () => {
const watcher = cwatch(currentDir, options);
const spy = await aspy(watcher, EV.ADD_DIR);
equal(spy.callCount, 1);
ok(calledWith(spy, [currentDir]));
});
it('should emit `addDir` events for preexisting dirs', async () => {
await mkdir(dpath('subdir'));
await mkdir(dpath('subdir/subsub'));
const watcher = cwatch(currentDir, options);
const spy = await aspy(watcher, EV.ADD_DIR);
ok(calledWith(spy, [currentDir]));
ok(calledWith(spy, [dpath('subdir')]));
ok(calledWith(spy, [dpath('subdir/subsub')]));
equal(spy.calls.length, 3);
});
});
describe('true', () => {
beforeEach(() => {
options.ignoreInitial = true;
});
it('should ignore initial add events', async () => {
const watcher = cwatch(currentDir, options);
const spy = await aspy(watcher, EV.ADD);
await delay();
equal(spy.called, false);
});
it('should ignore add events on a subsequent .add()', async () => {
const watcher = cwatch(dpath('subdir'), options);
const spy = await aspy(watcher, EV.ADD);
watcher.add(currentDir);
await delay(1000);
equal(spy.called, false);
});
it('should notice when a file appears in an empty directory', async () => {
const testDir = dpath('subdir');
const testPath = dpath('subdir/add.txt');
const spy = await aspy(cwatch(currentDir, options), EV.ADD);
equal(spy.called, false);
await mkdir(testDir);
await write(testPath, time());
await waitFor([spy]);
equal(spy.callCount, 1);
ok(calledWith(spy, [testPath]));
});
it('should emit a change on a preexisting file as a change', async () => {
const testPath = dpath('change.txt');
const spy = await aspy(cwatch(currentDir, options), EV.ALL);
equal(spy.called, false);
await write(testPath, time());
await waitFor([[spy, 1, [EV.CHANGE, testPath]]]);
ok(calledWith(spy, [EV.CHANGE, testPath]));
equal(calledWith(spy, [EV.ADD]), false);
});
it('should not emit for preexisting dirs when depth is 0', async () => {
options.depth = 0;
const testPath = dpath('add.txt');
await mkdir(dpath('subdir'));
await delay(200);
const spy = await aspy(cwatch(currentDir, options), EV.ALL);
await write(testPath, time());
await waitFor([spy]);
await delay(200);
ok(calledWith(spy, [EV.ADD, testPath]));
equal(calledWith(spy, [EV.ADD_DIR]), false);
});
});
});
describe('ignored', () => {
it('should check ignore after stating', async () => {
options.ignored = (path, stats) => {
if (upath.normalizeSafe(path) === upath.normalizeSafe(testDir) || !stats) return false;
return stats.isDirectory();
};
const testDir = dpath('subdir');
await mkdir(testDir);
await write(sp.join(testDir, 'add.txt'), '');
await mkdir(sp.join(testDir, 'subsub'));
await write(sp.join(testDir, 'subsub', 'ab.txt'), '');
const watcher = cwatch(testDir, options);
const spy = await aspy(watcher, EV.ADD);
equal(spy.callCount, 1);
ok(calledWith(spy, [sp.join(testDir, 'add.txt')]));
});
it('should not choke on an ignored watch path', async () => {
options.ignored = () => {
return true;
};
await waitForWatcher(cwatch(currentDir, options));
});
it('should ignore the contents of ignored dirs', async () => {
const testDir = dpath('subdir');
const testFile = sp.join(testDir, 'add.txt');
options.ignored = testDir;
await mkdir(testDir);
await write(testFile, 'b');
const watcher = cwatch(currentDir, options);
const spy = await aspy(watcher, EV.ALL);
await delay();
await write(testFile, time());
await delay(300);
equal(calledWith(spy, [EV.ADD_DIR, testDir]), false);
equal(calledWith(spy, [EV.ADD, testFile]), false);
equal(calledWith(spy, [EV.CHANGE, testFile]), false);
});
it('should allow regex/fn ignores', async () => {
options.cwd = currentDir;
options.ignored = /add/;
await write(dpath('add.txt'), 'b');
const watcher = cwatch(currentDir, options);
const spy = await aspy(watcher, EV.ALL);
await delay();
await write(dpath('add.txt'), time());
await write(dpath('change.txt'), time());
await waitFor([[spy, 1, [EV.CHANGE, 'change.txt']]]);
equal(calledWith(spy, [EV.ADD, 'add.txt']), false);
equal(calledWith(spy, [EV.CHANGE, 'add.txt']), false);
ok(calledWith(spy, [EV.ADD, 'change.txt']));
ok(calledWith(spy, [EV.CHANGE, 'change.txt']));
});
});
describe('depth', () => {
beforeEach(async () => {
await mkdir(dpath('subdir'));
await write(dpath('subdir/add.txt'), 'b');
await delay();
await mkdir(dpath('subdir/subsub'));
await write(dpath('subdir/subsub/ab.txt'), 'b');
await delay();
});
it('should not recurse if depth is 0', async () => {
options.depth = 0;
const watcher = cwatch(currentDir, options);
const spy = await aspy(watcher, EV.ALL);
await write(dpath('subdir/add.txt'), time());
await waitFor([[spy, 4]]);
ok(calledWith(spy, [EV.ADD_DIR, currentDir]));
ok(calledWith(spy, [EV.ADD_DIR, dpath('subdir')]));
ok(calledWith(spy, [EV.ADD, dpath('change.txt')]));
ok(calledWith(spy, [EV.ADD, dpath('unlink.txt')]));
equal(calledWith(spy, [EV.CHANGE]), false);
if (!macosFswatch) equal(spy.callCount, 4);
});
it('should recurse to specified depth', async () => {
options.depth = 1;
const addPath = dpath('subdir/add.txt');
const changePath = dpath('change.txt');
const ignoredPath = dpath('subdir/subsub/ab.txt');
const spy = await aspy(cwatch(currentDir, options), EV.ALL);
await delay();
await write(dpath('change.txt'), time());
await write(addPath, time());
await write(ignoredPath, time());
await waitFor([
[spy, 1, [EV.CHANGE, addPath]],
[spy, 1, [EV.CHANGE, changePath]],
]);
ok(calledWith(spy, [EV.ADD_DIR, dpath('subdir/subsub')]));
ok(calledWith(spy, [EV.CHANGE, changePath]));
ok(calledWith(spy, [EV.CHANGE, addPath]));
equal(calledWith(spy, [EV.ADD, ignoredPath]), false);
equal(calledWith(spy, [EV.CHANGE, ignoredPath]), false);
if (!macosFswatch) equal(spy.callCount, 8);
});
it('should respect depth setting when following symlinks', async () => {
if (isWindows) return true; // skip on windows
options.depth = 1;
await symlink(dpath('subdir'), dpath('link'), isWindows ? 'dir' : undefined);
await delay();
const spy = await aspy(cwatch(currentDir, options), EV.ALL);
ok(calledWith(spy, [EV.ADD_DIR, dpath('link')]));
ok(calledWith(spy, [EV.ADD_DIR, dpath('link/subsub')]));
ok(calledWith(spy, [EV.ADD, dpath('link/add.txt')]));
equal(calledWith(spy, [EV.ADD, dpath('link/subsub/ab.txt')]), false);
});
it('should respect depth setting when following a new symlink', async () => {
if (isWindows) return true; // skip on windows
options.depth = 1;
options.ignoreInitial = true;
const linkPath = dpath('link');
const dirPath = dpath('link/subsub');
const spy = await aspy(cwatch(currentDir, options), EV.ALL);
await symlink(dpath('subdir'), linkPath, isWindows ? 'dir' : undefined);
await waitFor([
[spy, 3],
[spy, 1, [EV.ADD_DIR, dirPath]],
]);
ok(calledWith(spy, [EV.ADD_DIR, linkPath]));
ok(calledWith(spy, [EV.ADD_DIR, dirPath]));
ok(calledWith(spy, [EV.ADD, dpath('link/add.txt')]));
equal(spy.calls.length, 3);
});
it('should correctly handle dir events when depth is 0', async () => {
options.depth = 0;
const subdir2 = dpath('subdir2');
const spy = await aspy(cwatch(currentDir, options), EV.ALL);
ok(calledWith(spy, [EV.ADD_DIR, currentDir]));
ok(calledWith(spy, [EV.ADD_DIR, dpath('subdir')]));
await mkdir(subdir2);
await waitFor([[spy, 3, [EV.ADD_DIR]]]);
equal(getCallsWith(spy, [EV.ADD_DIR]).length, 3);
await rmr(subdir2);
await waitFor([[spy, 1, [EV.UNLINK_DIR]]]);
await delay();
ok(calledWith(spy, [EV.UNLINK_DIR, subdir2]));
equal(getCallsWith(spy, [EV.UNLINK_DIR]).length, 1);
});
});
describe('atomic', () => {
beforeEach(() => {
options.atomic = true;
options.ignoreInitial = true;
});
it('should ignore vim/emacs/Sublime swapfiles', async () => {
const spy = await aspy(cwatch(currentDir, options), EV.ALL);
await write(dpath('.change.txt.swp'), 'a'); // vim
await write(dpath('add.txt~'), 'a'); // vim/emacs
await write(dpath('.subl5f4.tmp'), 'a'); // sublime
await delay(300);
await write(dpath('.change.txt.swp'), 'c');
await write(dpath('add.txt~'), 'c');
await write(dpath('.subl5f4.tmp'), 'c');
await delay(300);
await unlink(dpath('.change.txt.swp'));
await unlink(dpath('add.txt~'));
await unlink(dpath('.subl5f4.tmp'));
await delay(300);
equal(spy.called, false);
});
it('should ignore stale tilde files', async () => {
options.ignoreInitial = false;
await write(dpath('old.txt~'), 'a');
await delay();
const spy = await aspy(cwatch(currentDir, options), EV.ALL);
equal(calledWith(spy, [dpath('old.txt')]), false);
equal(calledWith(spy, [dpath('old.txt~')]), false);
});
});
describe('cwd', () => {
it('should emit relative paths based on cwd', async () => {
options.cwd = currentDir;
const watcher = cwatch('.', options);
const spy = await aspy(watcher, EV.ALL);
await unlink(dpath('unlink.txt'));
await write(dpath('change.txt'), time());
await waitFor([[spy, 1, [EV.UNLINK]]]);
ok(calledWith(spy, [EV.ADD, 'change.txt']));
ok(calledWith(spy, [EV.ADD, 'unlink.txt']));
ok(calledWith(spy, [EV.CHANGE, 'change.txt']));
ok(calledWith(spy, [EV.UNLINK, 'unlink.txt']));
});
it('should emit `addDir` with alwaysStat for renamed directory', async () => {
options.cwd = currentDir;
options.alwaysStat = true;
options.ignoreInitial = true;
const spy = createSpy();
const testDir = dpath('subdir');
const renamedDir = dpath('subdir-renamed');
await mkdir(testDir);
const watcher = cwatch('.', options);
await new Promise<void>((resolve) => {
setTimeout(async () => {
watcher.on(EV.ADD_DIR, spy);
await rename(testDir, renamedDir);
resolve();
}, 1000);
});
await waitFor([spy]);
equal(spy.callCount, 1);
ok(calledWith(spy, ['subdir-renamed']));
ok(spy.calls[0][1]); // stats
});
it('should allow separate watchers to have different cwds', async () => {
options.cwd = currentDir;
const options2: chokidar.ChokidarOptions = {};
Object.keys(options).forEach((key) => {
(options2 as Record<PropertyKey, unknown>)[key] =
options[key as keyof chokidar.ChokidarOptions];
});
options2.cwd = dpath('subdir');
const watcher = cwatch(gpath('.'), options);
const watcherEvents = waitForEvents(watcher, 5);
const spy1 = await aspy(watcher, EV.ALL);
await delay();
const watcher2 = cwatch(currentDir, options2);
const watcher2Events = waitForEvents(watcher2, 5);
const spy2 = await aspy(watcher2, EV.ALL);
await unlink(dpath('unlink.txt'));
await write(dpath('change.txt'), time());
await Promise.all([watcherEvents, watcher2Events]);
ok(calledWith(spy1, [EV.CHANGE, 'change.txt']));
ok(calledWith(spy1, [EV.UNLINK, 'unlink.txt']));
ok(calledWith(spy2, [EV.ADD, sp.join('..', 'change.txt')]));
ok(calledWith(spy2, [EV.ADD, sp.join('..', 'unlink.txt')]));
ok(calledWith(spy2, [EV.CHANGE, sp.join('..', 'change.txt')]));
ok(calledWith(spy2, [EV.UNLINK, sp.join('..', 'unlink.txt')]));
});
it('should ignore files even with cwd', async () => {
options.cwd = currentDir;
options.ignored = ['ignored-option.txt', 'ignored.txt'];
const files = ['.'];
await write(dpath('change.txt'), 'hello');
await write(dpath('ignored.txt'), 'ignored');
await write(dpath('ignored-option.txt'), 'ignored option');
const watcher = cwatch(files, options);
const spy = await aspy(watcher, EV.ALL);
await write(dpath('ignored.txt'), time());
await write(dpath('ignored-option.txt'), time());
await unlink(dpath('ignored.txt'));
await unlink(dpath('ignored-option.txt'));
await delay();
await write(dpath('change.txt'), EV.CHANGE);
await waitFor([[spy, 1, [EV.CHANGE, 'change.txt']]]);
ok(calledWith(spy, [EV.ADD, 'change.txt']));
equal(calledWith(spy, [EV.ADD, 'ignored.txt']), false);
equal(calledWith(spy, [EV.ADD, 'ignored-option.txt']), false);
equal(calledWith(spy, [EV.CHANGE, 'ignored.txt']), false);
equal(calledWith(spy, [EV.CHANGE, 'ignored-option.txt']), false);
equal(calledWith(spy, [EV.UNLINK, 'ignored.txt']), false);
equal(calledWith(spy, [EV.UNLINK, 'ignored-option.txt']), false);
ok(calledWith(spy, [EV.CHANGE, 'change.txt']));
});
});
describe('ignorePermissionErrors', () => {
let filePath: string;
beforeEach(async () => {
filePath = dpath('add.txt');
const PERM_R = 0o200;
await write(filePath, 'b', { mode: PERM_R });
await delay();
});
describe('false', () => {
beforeEach(() => {
options.ignorePermissionErrors = false;
// chokidar_watch();
});
it('should not watch files without read permissions', async () => {
if (isWindows) return true;
const spy = await aspy(cwatch(currentDir, options), EV.ALL);
equal(calledWith(spy, [EV.ADD, filePath]), false);
await write(filePath, time());
await delay(200);
equal(calledWith(spy, [EV.CHANGE, filePath]), false);
});
});
describe('true', () => {
beforeEach(() => {
options.ignorePermissionErrors = true;
});
it('should watch unreadable files if possible', async () => {
const spy = await aspy(cwatch(currentDir, options), EV.ALL);
ok(calledWith(spy, [EV.ADD, filePath]));
});
it('should not choke on non-existent files', async () => {
const watcher = cwatch(dpath('nope.txt'), options);
await waitForWatcher(watcher);
});
});
});
describe('awaitWriteFinish', () => {
beforeEach(() => {
options.awaitWriteFinish = { stabilityThreshold: 500 };
options.ignoreInitial = true;
});
it('should use default options if none given', () => {
options.awaitWriteFinish = true;
const watcher = cwatch(currentDir, options);
equal((watcher.options.awaitWriteFinish as chokidar.AWF).pollInterval, 100);
equal((watcher.options.awaitWriteFinish as chokidar.AWF).stabilityThreshold, 2000);
});
it('should not emit add event before a file is fully written', async () => {
const testPath = dpath('add.txt');
const spy = await aspy(cwatch(currentDir, options), EV.ALL);
await write(testPath, 'hello');
await delay(200);
equal(calledWith(spy, [EV.ADD]), false);
});
it('should wait for the file to be fully written before emitting the add event', async () => {
const testPath = dpath('add.txt');
const spy = await aspy(cwatch(currentDir, options), EV.ALL);
await write(testPath, 'hello');
await delay(300);
equal(spy.called, false);
await waitFor([spy]);
ok(calledWith(spy, [EV.ADD, testPath]));
});
it('should emit with the final stats', async () => {
const testPath = dpath('add.txt');
const spy = await aspy(cwatch(currentDir, options), EV.ALL);
await write(testPath, 'hello ');
await delay(300);
appendFile(testPath, 'world!');
await waitFor([spy]);
ok(calledWith(spy, [EV.ADD, testPath]));
equal(spy.calls[0][2].size, 12);
});
it('should not emit change event while a file has not been fully written', async () => {
const testPath = dpath('add.txt');
const spy = await aspy(cwatch(currentDir, options), EV.ALL);
await write(testPath, 'hello');
await delay(100);
await write(testPath, 'edit');
await delay(200);
equal(calledWith(spy, [EV.CHANGE, testPath]), false);
});
it('should not emit change event before an existing file is fully updated', async () => {
const testPath = dpath('change.txt');
const spy = await aspy(cwatch(currentDir, options), EV.ALL);
await write(testPath, 'hello');
await delay(300);
equal(calledWith(spy, [EV.CHANGE, testPath]), false);
});
it('should wait for an existing file to be fully updated before emitting the change event', async () => {
const testPath = dpath('change.txt');
const spy = await aspy(cwatch(currentDir, options), EV.ALL);
write(testPath, 'hello');
await delay(300);
equal(spy.called, false);
await waitFor([spy]);
ok(calledWith(spy, [EV.CHANGE, testPath]));
});
it('should emit change event after the file is fully written', async () => {
const testPath = dpath('add.txt');
const spy = await aspy(cwatch(currentDir, options), EV.ALL);
await delay();
await write(testPath, 'hello');
await waitFor([spy]);
ok(calledWith(spy, [EV.ADD, testPath]));
await write(testPath, 'edit');
await waitFor([[spy, 1, [EV.CHANGE]]]);
ok(calledWith(spy, [EV.CHANGE, testPath]));
});
it('should not raise any event for a file that was deleted before fully written', async () => {
const testPath = dpath('add.txt');
const spy = await aspy(cwatch(currentDir, options), EV.ALL);
await write(testPath, 'hello');
await delay(400);
await unlink(testPath);
await delay(400);
equal(
spy.calls.some((call) => typeof call[0] === 'string' && call[1] === testPath),
false
);
});
it('should be compatible with the cwd option', async () => {
const testPath = dpath('subdir/add.txt');
const filename = sp.basename(testPath);
options.cwd = sp.dirname(testPath);
await mkdir(options.cwd);
await delay(200);
const spy = await aspy(cwatch(currentDir, options), EV.ALL);
await delay(400);
await write(testPath, 'hello');
await waitFor([[spy, 1, [EV.ADD]]]);
ok(calledWith(spy, [EV.ADD, filename]));
});
it('should still emit initial add events', async () => {
options.ignoreInitial = false;
const spy = await aspy(cwatch(currentDir, options), EV.ALL);
ok(calledWith(spy, [EV.ADD]));
ok(calledWith(spy, [EV.ADD_DIR]));
});
it('should emit an unlink event when a file is updated and deleted just after that', async () => {
const testPath = dpath('subdir/add.txt');
const filename = sp.basename(testPath);
options.cwd = sp.dirname(testPath);
await mkdir(options.cwd);
await delay();
await write(testPath, 'hello');
await delay();
const spy = await aspy(cwatch(currentDir, options), EV.ALL);
await write(testPath, 'edit');
await delay();
await unlink(testPath);
await waitFor([[spy, 1, [EV.UNLINK]]]);
ok(calledWith(spy, [EV.UNLINK, filename]));
equal(calledWith(spy, [EV.CHANGE, filename]), false);
});
});
});
describe('getWatched', () => {
it('should return the watched paths', async () => {
const expected: Record<string, string[]> = {};
expected[sp.dirname(currentDir)] = [testId.toString()];
expected[currentDir] = ['change.txt', 'unlink.txt'];
const watcher = cwatch(currentDir, options);
await waitForWatcher(watcher);
deepEqual(watcher.getWatched(), expected);
});
it('should set keys relative to cwd & include added paths', async () => {
options.cwd = currentDir;
const expected = {
'.': ['change.txt', 'subdir', 'unlink.txt'],
'..': [testId.toString()],
subdir: [],
};
await mkdir(dpath('subdir'));
const watcher = cwatch(currentDir, options);
await waitForWatcher(watcher);
deepEqual(watcher.getWatched(), expected);
});
});
describe('unwatch', () => {
beforeEach(async () => {
options.ignoreInitial = true;
await mkdir(dpath('subdir'));
await delay();
});
it('should stop watching unwatched paths', async () => {
const watchPaths = [dpath('subdir'), dpath('change.txt')];
const watcher = cwatch(watchPaths, options);
const spy = await aspy(watcher, EV.ALL);
watcher.unwatch(dpath('subdir'));
await delay();
await write(dpath('subdir/add.txt'), time());
await write(dpath('change.txt'), time());
await waitFor([spy]);
await delay(300);
ok(calledWith(spy, [EV.CHANGE, dpath('change.txt')]));
equal(calledWith(spy, [EV.ADD]), false);
if (!macosFswatch) equal(spy.callCount, 1);
});
it('should ignore unwatched paths that are a subset of watched paths', async () => {
const subdirRel = upath.relative(process.cwd(), dpath('subdir'));
const unlinkFile = dpath('unlink.txt');
const addFile = dpath('subdir/add.txt');
const changedFile = dpath('change.txt');
const watcher = cwatch(currentDir, options);
const spy = await aspy(watcher, EV.ALL);
// test with both relative and absolute paths
watcher.unwatch([subdirRel, gpath('unlink.txt')]);
await delay();
await unlink(unlinkFile);
await write(addFile, time());
await write(changedFile, time());
await waitFor([[spy, 1, [EV.CHANGE]]]);
await delay(300);
ok(calledWith(spy, [EV.CHANGE, changedFile]));
equal(calledWith(spy, [EV.ADD, addFile]), false);
equal(calledWith(spy, [EV.UNLINK, unlinkFile]), false);
if (!macosFswatch) equal(spy.callCount, 1);
});
it('should unwatch relative paths', async () => {
const fixturesDir = sp.relative(process.cwd(), currentDir);
const subdir = sp.join(fixturesDir, 'subdir');
const changeFile = sp.join(fixturesDir, 'change.txt');
const watchPaths = [subdir, changeFile];
const watcher = cwatch(watchPaths, options);
const spy = await aspy(watcher, EV.ALL);
await delay();
watcher.unwatch(subdir);
await write(dpath('subdir/add.txt'), time());
await write(dpath('change.txt'), time());
await waitFor([spy]);
await delay(300);
ok(calledWith(spy, [EV.CHANGE, changeFile]));
equal(calledWith(spy, [EV.ADD]), false);
if (!macosFswatch) equal(spy.callCount, 1);
});
it.skip('should watch paths that were unwatched and added again', async () => {
const spy = createSpy();
const watchPaths = [dpath('change.txt')];
console.log('watching', watchPaths);
const watcher = cwatch(watchPaths, options).on(EV.ALL, console.log.bind(console));
await waitForWatcher(watcher);
await delay();
watcher.unwatch(dpath('change.txt'));
await delay();
watcher.on(EV.ALL, spy).add(dpath('change.txt'));
await delay();
await write(dpath('change.txt'), time());
console.log('a');
await waitFor([spy]);
console.log('b');
ok(calledWith(spy, [EV.CHANGE, dpath('change.txt')]));
if (!macosFswatch) equal(spy.callCount, 1);
});
it('should unwatch paths that are relative to options.cwd', async () => {
options.cwd = currentDir;
const watcher = cwatch('.', options);
const spy = await aspy(watcher, EV.ALL);
watcher.unwatch(['subdir', dpath('unlink.txt')]);
await delay();
await unlink(dpath('unlink.txt'));
await write(dpath('subdir/add.txt'), time());
await write(dpath('change.txt'), time());
await waitFor([spy]);
await delay(300);
ok(calledWith(spy, [EV.CHANGE, 'change.txt']));
equal(calledWith(spy, [EV.ADD]), false);
equal(calledWith(spy, [EV.UNLINK]), false);
if (!macosFswatch) equal(spy.callCount, 1);
});
});
describe('env variable option override', () => {
describe('CHOKIDAR_USEPOLLING', () => {
afterEach(() => {
delete process.env.CHOKIDAR_USEPOLLING;
});
it('should make options.usePolling `true` when CHOKIDAR_USEPOLLING is set to true', async () => {
options.usePolling = false;
process.env.CHOKIDAR_USEPOLLING = 'true';
const watcher = cwatch(currentDir, options);
await waitForWatcher(watcher);
equal(watcher.options.usePolling, true);
});
it('should make options.usePolling `true` when CHOKIDAR_USEPOLLING is set to 1', async () => {
options.usePolling = false;
process.env.CHOKIDAR_USEPOLLING = '1';
const watcher = cwatch(currentDir, options);
await waitForWatcher(watcher);
equal(watcher.options.usePolling, true);
});
it('should make options.usePolling `false` when CHOKIDAR_USEPOLLING is set to false', async () => {
options.usePolling = true;
process.env.CHOKIDAR_USEPOLLING = 'false';
const watcher = cwatch(currentDir, options);
await waitForWatcher(watcher);
equal(watcher.options.usePolling, false);
});
it('should make options.usePolling `false` when CHOKIDAR_USEPOLLING is set to 0', async () => {
options.usePolling = true;
process.env.CHOKIDAR_USEPOLLING = 'false';
const watcher = cwatch(currentDir, options);
await waitForWatcher(watcher);
equal(watcher.options.usePolling, false);
});
it('should not attenuate options.usePolling when CHOKIDAR_USEPOLLING is set to an arbitrary value', async () => {
options.usePolling = true;
process.env.CHOKIDAR_USEPOLLING = 'foo';
const watcher = cwatch(currentDir, options);
await waitForWatcher(watcher);
equal(watcher.options.usePolling, true);
});
});
if (options && options.usePolling) {
describe('CHOKIDAR_INTERVAL', () => {
afterEach(() => {
delete process.env.CHOKIDAR_INTERVAL;
});
it('should make options.interval = CHOKIDAR_INTERVAL when it is set', async () => {
options.interval = 100;
process.env.CHOKIDAR_INTERVAL = '1500';
const watcher = cwatch(currentDir, options);
await waitForWatcher(watcher);
equal(watcher.options.interval, 1500);
});
});
}
});
describe('reproduction of bug in issue #1040', () => {
it('should detect change on symlink folders when consolidateThreshhold is reached', async () => {
const CURR = sp.join(FIXTURES_PATH, testId.toString());
const fixturesPathRel = sp.join(CURR, 'test-case-1040');
const linkPath = sp.join(fixturesPathRel, 'symlinkFolder');
const packagesPath = sp.join(fixturesPathRel, 'packages');
await mkdir(fixturesPathRel, { recursive: true });
await mkdir(linkPath);
await mkdir(packagesPath);
// Init chokidar
const watcher = cwatch([]);
// Add more than 10 folders to cap consolidateThreshhold
for (let i = 0; i < 20; i += 1) {
const folderPath = sp.join(packagesPath, `folder${i}`);
await mkdir(folderPath);
const filePath = sp.join(folderPath, `file${i}.js`);
await write(sp.resolve(filePath), 'file content');
const symlinkPath = sp.join(linkPath, `folder${i}`);
await symlink(sp.resolve(folderPath), symlinkPath, isWindows ? 'dir' : undefined);
watcher.add(sp.resolve(sp.join(symlinkPath, `file${i}.js`)));
}
// Wait to be sure that we have no other event than the update file
await delay(300);
const eventsWaiter = waitForEvents(watcher, 1);
// Update a random generated file to fire an event
const randomFilePath = sp.join(packagesPath, 'folder17', 'file17.js');
await write(sp.resolve(randomFilePath), 'file content changer zeri ezhriez');
// Wait chokidar watch
await delay(300);
const events = await eventsWaiter;
equal(events.length, 1);
});
});
describe('reproduction of bug in issue #1024', () => {
it('should detect changes to folders, even if they were deleted before', async () => {
const id = testId.toString();
const absoluteWatchedDir = sp.join(FIXTURES_PATH, id, 'test');
const relativeWatcherDir = sp.join(id, 'test');
const watcher = cwatch(relativeWatcherDir, {
persistent: true,
});
try {
const eventsWaiter = waitForEvents(watcher, 5);
const testSubDir = sp.join(absoluteWatchedDir, 'dir');
const testSubDirFile = sp.join(absoluteWatchedDir, 'dir', 'file');
// Command sequence from https://github.com/paulmillr/chokidar/issues/1042.
await delay();
await mkdir(absoluteWatchedDir);
await mkdir(testSubDir);
// The following delay is essential otherwise the call of mkdir and rm will be equalize
await delay(300);
await rmr(testSubDir);
// The following delay is essential otherwise the call of rm and mkdir will be equalize
await delay(300);
await mkdir(testSubDir);
await delay(300);
await write(testSubDirFile, '');
await delay(300);
const events = await eventsWaiter;
deepEqual(events, [
`[ALL] addDir: ${sp.join(id, 'test')}`,
`[ALL] addDir: ${sp.join(id, 'test', 'dir')}`,
`[ALL] unlinkDir: ${sp.join(id, 'test', 'dir')}`,
`[ALL] addDir: ${sp.join(id, 'test', 'dir')}`,
`[ALL] add: ${sp.join(id, 'test', 'dir', 'file')}`,
]);
} finally {
watcher.close();
}
});
it('should detect changes to symlink folders, even if they were deleted before', async () => {
const id = testId.toString();
const relativeWatcherDir = sp.join(id, 'test');
const linkedRelativeWatcherDir = sp.join(id, 'test-link');
await symlink(
sp.resolve(relativeWatcherDir),
linkedRelativeWatcherDir,
isWindows ? 'dir' : undefined
);
await delay();
const watcher = cwatch(linkedRelativeWatcherDir, {
persistent: true,
});
try {
const eventsWaiter = waitForEvents(watcher, 5);
const testSubDir = sp.join(relativeWatcherDir, 'dir');
const testSubDirFile = sp.join(relativeWatcherDir, 'dir', 'file');
// Command sequence from https://github.com/paulmillr/chokidar/issues/1042.
await delay();
await mkdir(relativeWatcherDir);
await mkdir(testSubDir);
// The following delay is essential otherwise the call of mkdir and rm will be equalize
await delay(300);
await rmr(testSubDir);
// The following delay is essential otherwise the call of rm and mkdir will be equalize
await delay(300);
await mkdir(testSubDir);
await delay(300);
await write(testSubDirFile, '');
await delay(300);
const events = await eventsWaiter;
deepEqual(events, [
`[ALL] addDir: ${sp.join(id, 'test-link')}`,
`[ALL] addDir: ${sp.join(id, 'test-link', 'dir')}`,
`[ALL] unlinkDir: ${sp.join(id, 'test-link', 'dir')}`,
`[ALL] addDir: ${sp.join(id, 'test-link', 'dir')}`,
`[ALL] add: ${sp.join(id, 'test-link', 'dir', 'file')}`,
]);
} finally {
watcher.close();
}
});
});
describe('close', () => {
it('should ignore further events on close', async () => {
const spy = createSpy();
const watcher = cwatch(currentDir, options);
await waitForWatcher(watcher);
watcher.on(EV.ALL, spy);
await watcher.close();
await write(dpath('add.txt'), time());
await write(dpath('add.txt'), 'hello');
await delay(300);
await unlink(dpath('add.txt'));
equal(spy.called, false);
});
it('should not ignore further events on close with existing watchers', async () => {
const spy = createSpy();
const watcher1 = cwatch(currentDir);
const watcher2 = cwatch(currentDir);
await Promise.all([waitForWatcher(watcher1), waitForWatcher(watcher2)]);
// The EV_ADD event should be called on the second watcher even if the first watcher is closed
watcher2.on(EV.ADD, spy);
await watcher1.close();
await write(dpath('add.txt'), 'hello');
// Ensures EV_ADD is called. Immediately removing the file causes it to be skipped
await delay(200);
await unlink(dpath('add.txt'));
ok(spy.calls.some((call) => call[0].includes('add.txt')));
});
it('should not prevent the process from exiting', async () => {
function rmSlashes(str: string) {
return str.replace(/\\/g, '\\\\');
}
const _dirname = fileURLToPath(new URL('.', imetaurl)); // Will contain trailing slash
const chokidarPath = rmSlashes(pathToFileURL(sp.join(_dirname, 'index.js')).href);
const scriptFile = dpath('script.js');
const scriptContent = `
(async () => {
const chokidar = await import("${chokidarPath}");
const watcher = chokidar.watch("${rmSlashes(scriptFile)}");
watcher.on("ready", () => {
watcher.close();
process.stdout.write("closed");
});
})();`;
await write(scriptFile, scriptContent);
const obj = await exec(`node ${scriptFile}`);
const { stdout } = obj;
equal(stdout.toString(), 'closed');
});
it('should always return the same promise', async () => {
const watcher = cwatch(currentDir, options);
const closePromise = watcher.close();
ok(closePromise instanceof Promise);
equal(watcher.close(), closePromise);
await closePromise;
});
});
};
describe('chokidar', async () => {
beforeEach(() => {
testId++;
currentDir = dpath('');
});
afterEach(async () => {
const promises = WATCHERS.map((w) => w.close());
await Promise.all(promises);
await rmr(currentDir);
});
it('should expose public API methods', () => {
ok(typeof chokidar.FSWatcher === 'function');
ok(typeof chokidar.watch === 'function');
});
if (!isIBMi) {
describe('fs.watch (non-polling)', runTests.bind(this, { usePolling: false }));
}
describe('fs.watchFile (polling)', runTests.bind(this, { usePolling: true, interval: 10 }));
});
async function main() {
const initialPath = process.cwd();
try {
await rmr(FIXTURES_PATH);
await mkdir(FIXTURES_PATH, { recursive: true });
} catch (error) {}
process.chdir(FIXTURES_PATH);
// Create many directories before tests.
// Creating them in `beforeEach` increases chance of random failures.
const _filename = fileURLToPath(new URL('', imetaurl));
const _content = await read(_filename, 'utf-8');
const _only = _content.match(/\sit\.only\(/g);
const itCount = (_only && _only.length) || _content.match(/\sit\(/g)?.length;
const testCount = (itCount ?? 0) * 3;
while (testId++ < testCount) {
await mkdir(dpath(''));
await write(dpath('change.txt'), 'b');
await write(dpath('unlink.txt'), 'b');
}
testId = 0;
await it.run(true);
try {
await rmr(FIXTURES_PATH);
} catch (error) {
console.error('test clean-up error', error);
}
process.chdir(initialPath);
}
main();
================================================
FILE: src/index.ts
================================================
/*! chokidar - MIT License (c) 2012 Paul Miller (paulmillr.com) */
import type { Stats } from 'node:fs';
import { EventEmitter } from 'node:events';
import { stat as statcb } from 'node:fs';
import { readdir, stat } from 'node:fs/promises';
import * as sp from 'node:path';
import { type EntryInfo, readdirp, type ReaddirpOptions, ReaddirpStream } from 'readdirp';
import {
EMPTY_FN,
EVENTS as EV,
type EventName,
isIBMi,
isWindows,
NodeFsHandler,
type Path,
STR_CLOSE,
STR_END,
type WatchHandlers,
} from './handler.js';
export type AWF = {
stabilityThreshold: number;
pollInterval: number;
};
type BasicOpts = {
persistent: boolean;
ignoreInitial: boolean;
followSymlinks: boolean;
cwd?: string;
// Polling
usePolling: boolean;
interval: number;
binaryInterval: number; // Used only for pooling and if different from interval
alwaysStat?: boolean;
depth?: number;
ignorePermissionErrors: boolean;
atomic: boolean | number; // or a custom 'atomicity delay', in milliseconds (default 100)
// useAsync?: boolean; // Use async for stat/readlink methods
// ioLimit?: number; // Limit parallel IO operations (CPU usage + OS limits)
};
export type Throttler = {
timeoutObject: NodeJS.Timeout;
clear: () => void;
count: number;
};
export type ChokidarOptions = Partial<
BasicOpts & {
ignored: Matcher | Matcher[];
awaitWriteFinish: boolean | Partial<AWF>;
}
>;
export type FSWInstanceOptions = BasicOpts & {
ignored: Matcher[]; // string | fn ->
awaitWriteFinish: false | AWF;
};
export type ThrottleType = 'readdir' | 'watch' | 'add' | 'remove' | 'change';
export type EmitArgs = [path: Path, stats?: Stats];
export type EmitErrorArgs = [error: Error, stats?: Stats];
export type EmitArgsWithName = [event: EventName, ...EmitArgs];
export type MatchFunction = (val: string, stats?: Stats) => boolean;
export interface MatcherObject {
path: string;
recursive?: boolean;
}
export type Matcher = string | RegExp | MatchFunction | MatcherObject;
const SLASH = '/';
const SLASH_SLASH = '//';
const ONE_DOT = '.';
const TWO_DOTS = '..';
const STRING_TYPE = 'string';
const BACK_SLASH_RE = /\\/g;
const DOUBLE_SLASH_RE = /\/\//g;
const DOT_RE = /\..*\.(sw[px])$|~$|\.subl.*\.tmp/;
const REPLACER_RE = /^\.[/\\]/;
function arrify<T>(item: T | T[]): T[] {
return Array.isArray(item) ? item : [item];
}
const isMatcherObject = (matcher: Matcher): matcher is MatcherObject =>
typeof matcher === 'object' && matcher !== null && !(matcher instanceof RegExp);
function createPattern(matcher: Matcher): MatchFunction {
if (typeof matcher === 'function') return matcher;
if (typeof matcher === 'string') return (string) => matcher === string;
if (matcher instanceof RegExp) return (string) => matcher.test(string);
if (typeof matcher === 'object' && matcher !== null) {
return (string) => {
if (matcher.path === string) return true;
if (matcher.recursive) {
const relative = sp.relative(matcher.path, string);
if (!relative) {
return false;
}
return !relative.startsWith('..') && !sp.isAbsolute(relative);
}
return false;
};
}
return () => false;
}
function normalizePath(path: Path): Path {
if (typeof path !== 'string') throw new Error('string expected');
path = sp.normalize(path);
path = path.replace(/\\/g, '/');
let prepend = false;
if (path.startsWith('//')) prepend = true;
path = path.replace(DOUBLE_SLASH_RE, '/');
if (prepend) path = '/' + path;
return path;
}
function matchPatterns(patterns: MatchFunction[], testString: string, stats?: Stats): boolean {
const path = normalizePath(testString);
for (let index = 0; index < patterns.length; index++) {
const pattern = patterns[index];
if (pattern(path, stats)) {
return true;
}
}
return false;
}
function anymatch(matchers: Matcher[], testString: undefined): MatchFunction;
function anymatch(matchers: Matcher[], testString: string): boolean;
function anymatch(matchers: Matcher[], testString: string | undefined): boolean | MatchFunction {
if (matchers == null) {
throw new TypeError('anymatch: specify first argument');
}
// Early cache for matchers.
const matchersArray = arrify(matchers);
const patterns = matchersArray.map((matcher) => createPattern(matcher));
if (testString == null) {
return (testString: string, stats?: Stats): boolean => {
return matchPatterns(patterns, testString, stats);
};
}
return matchPatterns(patterns, testString);
}
const unifyPaths = (paths_: Path | Path[]) => {
const paths = arrify(paths_).flat();
if (!paths.every((p) => typeof p === STRING_TYPE)) {
throw new TypeError(`Non-string provided as watch path: ${paths}`);
}
return paths.map(normalizePathToUnix);
};
// If SLASH_SLASH occurs at the beginning of path, it is not replaced
// because "//StoragePC/DrivePool/Movies" is a valid network path
const toUnix = (string: string) => {
let str = string.replace(BACK_SLASH_RE, SLASH);
let prepend = false;
if (str.startsWith(SLASH_SLASH)) {
prepend = true;
}
str = str.replace(DOUBLE_SLASH_RE, SLASH);
if (prepend) {
str = SLASH + str;
}
return str;
};
// Our version of upath.normalize
// TODO: this is not equal to path-normalize module - investigate why
const normalizePathToUnix = (path: Path) => toUnix(sp.normalize(toUnix(path)));
// TODO: refactor
const normalizeIgnored =
(cwd = '') =>
(path: Matcher): Matcher => {
if (typeof path === 'string') {
return normalizePathToUnix(sp.isAbsolute(path) ? path : sp.join(cwd, path));
} else {
return path;
}
};
const getAbsolutePath = (path: Path, cwd: Path) => {
if (sp.isAbsolute(path)) {
return path;
}
return sp.join(cwd, path);
};
const EMPTY_SET = Object.freeze(new Set<string>());
/**
* Directory entry.
*/
class DirEntry {
path: Path;
_removeWatcher: (dir: string, base: string) => void;
items: Set<Path>;
constructor(dir: Path, removeWatcher: (dir: string, base: string) => void) {
this.path = dir;
this._removeWatcher = removeWatcher;
this.items = new Set<Path>();
}
add(item: string): void {
const { items } = this;
if (!items) return;
if (item !== ONE_DOT && item !== TWO_DOTS) items.add(item);
}
async remove(item: string): Promise<void> {
const { items } = this;
if (!items) return;
items.delete(item);
if (items.size > 0) return;
const dir = this.path;
try {
await readdir(dir);
} catch (err) {
if (this._removeWatcher) {
this._removeWatcher(sp.dirname(dir), sp.basename(dir));
}
}
}
has(item: string): boolean | undefined {
const { items } = this;
if (!items) return;
return items.has(item);
}
getChildren(): string[] {
const { items } = this;
if (!items) return [];
return [...items.values()];
}
dispose(): void {
this.items.clear();
this.path = '';
this._removeWatcher = EMPTY_FN;
this.items = EMPTY_SET;
Object.freeze(this);
}
}
const STAT_METHOD_F = 'stat';
const STAT_METHOD_L = 'lstat';
export class WatchHelper {
fsw: FSWatcher;
path: string;
watchPath: string;
fullWatchPath: string;
dirParts: string[][];
followSymlinks: boolean;
statMethod: 'stat' | 'lstat';
constructor(path: string, follow: boolean, fsw: FSWatcher) {
this.fsw = fsw;
const watchPath = path;
this.path = path = path.replace(REPLACER_RE, '');
this.watchPath = watchPath;
this.fullWatchPath = sp.resolve(watchPath);
this.dirParts = [];
this.dirParts.forEach((parts) => {
if (parts.length > 1) parts.pop();
});
this.followSymlinks = follow;
this.statMethod = follow ? STAT_METHOD_F : STAT_METHOD_L;
}
entryPath(entry: EntryInfo): Path {
return sp.join(this.watchPath, sp.relative(this.watchPath, entry.fullPath));
}
filterPath(entry: EntryInfo): boolean {
const { stats } = entry;
if (stats && stats.isSymbolicLink()) return this.filterDir(entry);
const resolvedPath = this.entryPath(entry);
// TODO: what if stats is undefined? remove !
return this.fsw._isntIgnored(resolvedPath, stats) && this.fsw._hasReadPermissions(stats!);
}
filterDir(entry: EntryInfo): boolean {
return this.fsw._isntIgnored(this.entryPath(entry), entry.stats);
}
}
export interface FSWatcherEventMap {
[EV.READY]: [];
[EV.RAW]: Parameters<WatchHandlers['rawEmitter']>;
[EV.ERROR]: Parameters<WatchHandlers['errHandler']>;
[EV.ALL]: [event: EventName, ...EmitArgs];
[EV.ADD]: EmitArgs;
[EV.CHANGE]: EmitArgs;
[EV.ADD_DIR]: EmitArgs;
[EV.UNLINK]: EmitArgs;
[EV.UNLINK_DIR]: EmitArgs;
}
/**
* Watches files & directories for changes. Emitted events:
* `add`, `addDir`, `change`, `unlink`, `unlinkDir`, `all`, `error`
*
* new FSWatcher()
* .add(directories)
* .on('add', path => log('File', path, 'was added'))
*/
export class FSWatcher extends EventEmitter<FSWatcherEventMap> {
closed: boolean;
options: FSWInstanceOptions;
_closers: Map<string, Array<any>>;
_ignoredPaths: Set<Matcher>;
_throttled: Map<ThrottleType, Map<any, any>>;
_streams: Set<ReaddirpStream>;
_symlinkPaths: Map<Path, string | boolean>;
_watched: Map<string, DirEntry>;
_pendingWrites: Map<string, any>;
_pendingUnlinks: Map<string, EmitArgsWithName>;
_readyCount: number;
_emitReady: () => void;
_closePromise?: Promise<void>;
_userIgnored?: MatchFunction;
_readyEmitted: boolean;
_emitRaw: WatchHandlers['rawEmitter'];
_boundRemove: (dir: string, item: string) => void;
_nodeFsHandler: NodeFsHandler;
// Not indenting methods for history sake; for now.
constructor(_opts: ChokidarOptions = {}) {
super();
this.closed = false;
this._closers = new Map();
this._ignoredPaths = new Set<Matcher>();
this._throttled = new Map();
this._streams = new Set();
this._symlinkPaths = new Map();
this._watched = new Map();
this._pendingWrites = new Map();
this._pendingUnlinks = new Map();
this._readyCount = 0;
this._readyEmitted = false;
const awf = _opts.awaitWriteFinish;
const DEF_AWF = { stabilityThreshold: 2000, pollInterval: 100 };
const opts: FSWInstanceOptions = {
// Defaults
persistent: true,
ignoreInitial: false,
ignorePermissionErrors: false,
interval: 100,
binaryInterval: 300,
followSymlinks: true,
usePolling: false,
// useAsync: false,
atomic: true, // NOTE: overwritten later (depends on usePolling)
..._opts,
// Change format
ignored: _opts.ignored ? arrify(_opts.ignored) : arrify([]),
awaitWriteFinish:
awf === true ? DEF_AWF : typeof awf === 'object' ? { ...DEF_AWF, ...awf } : false,
};
// Always default to polling on IBM i because fs.watch() is not available on IBM i.
if (isIBMi) opts.usePolling = true;
// Editor atomic write normalization enabled by default with fs.watch
if (opts.atomic === undefined) opts.atomic = !opts.usePolling;
// opts.atomic = typeof _opts.atomic === 'number' ? _opts.atomic : 100;
// Global override. Useful for developers, who need to force polling for all
// instances of chokidar, regardless of usage / dependency depth
const envPoll = process.env.CHOKIDAR_USEPOLLING;
if (envPoll !== undefined) {
const envLower = envPoll.toLowerCase();
if (envLower === 'false' || envLower === '0') opts.usePolling = false;
else if (envLower === 'true' || envLower === '1') opts.usePolling = true;
else opts.usePolling = !!envLower;
}
const envInterval = process.env.CHOKIDAR_INTERVAL;
if (envInterval) opts.interval = Number.parseInt(envInterval, 10);
// This is done to emit ready only once, but each 'add' will increase that?
let readyCalls = 0;
this._emitReady = () => {
readyCalls++;
if (readyCalls >= this._readyCount) {
this._emitReady = EMPTY_FN;
this._readyEmitted = true;
// use process.nextTick to allow time for listener to be bound
process.nextTick(() => this.emit(EV.READY));
}
};
this._emitRaw = (...args) => this.emit(EV.RAW, ...args);
this._boundRemove = this._remove.bind(this);
this.options = opts;
this._nodeFsHandler = new NodeFsHandler(this);
// You’re frozen when your heart’s not open.
Object.freeze(opts);
}
_addIgnoredPath(matcher: Matcher): void {
if (isMatcherObject(matcher)) {
// return early if we already have a deeply equal matcher object
for (const ignored of this._ignoredPaths) {
if (
isMatcherObject(ignored) &&
ignored.path === matcher.path &&
ignored.recursive === matcher.recursive
) {
return;
}
}
}
this._ignoredPaths.add(matcher);
}
_removeIgnoredPath(matcher: Matcher): void {
this._ignoredPaths.delete(matcher);
// now find any matcher objects with the matcher as path
if (typeof matcher === 'string') {
for (const ignored of this._ignoredPaths) {
// TODO (43081j): make this more efficient.
// probably just make a `this._ignoredDirectories` or some
// such thing.
if (isMatcherObject(ignored) && ignored.path === matcher) {
this._ignoredPaths.delete(ignored);
}
}
}
}
// Public methods
/**
* Adds paths to be watched on an existing FSWatcher instance.
* @param paths_ file or file list. Other arguments are unused
*/
add(paths_: Path | Path[], _origAdd?: string, _internal?: boolean): FSWatcher {
const { cwd } = this.options;
this.closed = false;
this._closePromise = undefined;
let paths = unifyPaths(paths_);
if (cwd) {
paths = paths.map((path) => {
const absPath = getAbsolutePath(path, cwd);
// Check `path` instead of `absPath` because the cwd portion can't be a glob
return absPath;
});
}
paths.forEach((path) => {
this._removeIgnoredPath(path);
});
this._userIgnored = undefined;
if (!this._readyCount) this._readyCount = 0;
this._readyCount += paths.length;
Promise.all(
paths.map(async (path) => {
const res = await this._nodeFsHandler._addToNodeFs(
path,
!_internal,
undefined,
0,
_origAdd
);
if (res) this._emitReady();
return res;
})
).then((results) => {
if (this.closed) return;
results.forEach((item) => {
if (item) this.add(sp.dirname(item), sp.basename(_origAdd || item));
});
});
return this;
}
/**
* Close watchers or start ignoring events from specified paths.
*/
unwatch(paths_: Path | Path[]): FSWatcher {
if (this.closed) return this;
const paths = unifyPaths(paths_);
const { cwd } = this.options;
paths.forEach((path) => {
// convert to absolute path unless relative path already matches
if (!sp.isAbsolute(path) && !this._closers.has(path)) {
if (cwd) path = sp.join(cwd, path);
path = sp.resolve(path);
}
this._closePath(path);
this._addIgnoredPath(path);
if (this._watched.has(path)) {
this._addIgnoredPath({
path,
recursive: true,
});
}
// reset the cached userIgnored anymatch fn
// to make ignoredPaths changes effective
this._userIgnored = undefined;
});
return this;
}
/**
* Close watchers and remove all listeners from watched paths.
*/
close(): Promise<void> {
if (this._closePromise) {
return this._closePromise;
}
this.closed = true;
// Memory management.
this.removeAllListeners();
const closers: Array<Promise<void>> = [];
this._closers.forEach((closerList) =>
closerList.forEach((closer) => {
const promise = closer();
if (promise instanceof Promise) closers.push(promise);
})
);
this._streams.forEach((stream) => stream.destroy());
this._userIgnored = undefined;
this._readyCount = 0;
this._readyEmitted = false;
this._watched.forEach((dirent) => dirent.dispose());
this._closers.clear();
this._watched.clear();
this._streams.clear();
this._symlinkPaths.clear();
this._throttled.clear();
this._closePromise = closers.length
? Promise.all(closers).then(() => undefined)
: Promise.resolve();
return this._closePromise;
}
/**
* Expose list of watched paths
* @returns for chaining
*/
getWatched(): Record<string, string[]> {
const watchList: Record<string, string[]> = {};
this._watched.forEach((entry, dir) => {
const key = this.options.cwd ? sp.relative(this.options.cwd, dir) : dir;
const index = key || ONE_DOT;
watchList[index] = entry.getChildren().sort();
});
return watchList;
}
emitWithAll(event: EventName, args: EmitArgs): void {
this.emit(event, ...args);
if (event !== EV.ERROR) this.emit(EV.ALL, event, ...args);
}
// Common helpers
// --------------
/**
* Normalize and emit events.
* Calling _emit DOES NOT MEAN emit() would be called!
* @param event Type of event
* @param path File or directory path
* @param stats arguments to be passed with event
* @returns the error if defined, otherwise the value of the FSWatcher instance's `closed` flag
*/
async _emit(event: EventName, path: Path, stats?: Stats): Promise<this | undefined> {
if (this.closed) return;
const opts = this.options;
if (isWindows) path = sp.normalize(path);
if (opts.cwd) path = sp.relative(opts.cwd, path);
const args: EmitArgs | EmitErrorArgs = [path];
if (stats != null) args.push(stats);
const awf = opts.awaitWriteFinish;
let pw;
if (awf && (pw = this._pendingWrites.get(path))) {
pw.lastChange = new Date();
return this;
}
if (opts.atomic) {
if (event === EV.UNLINK) {
this._pendingUnlinks.set(path, [event, ...args]);
setTimeout(
() => {
this._pendingUnlinks.forEach((entry: EmitArgsWithName, path: Path) => {
this.emit(...entry);
this.emit(EV.ALL, ...entry);
this._pendingUnlinks.delete(path);
});
},
typeof opts.atomic === 'number' ? opts.atomic : 100
);
return this;
}
if (event === EV.ADD && this._pendingUnlinks.has(path)) {
event = EV.CHANGE;
this._pendingUnlinks.delete(path);
}
}
if (awf && (event === EV.ADD || event === EV.CHANGE) && this._readyEmitted) {
const awfEmit = (err?: Error, stats?: Stats) => {
if (err) {
event = EV.ERROR;
(args as unknown as EmitErrorArgs)[0] = err;
this.emitWithAll(event, args);
} else if (stats) {
// if stats doesn't exist the file must have been deleted
if (args.length > 1) {
args[1] = stats;
} else {
args.push(stats);
}
this.emitWithAll(event, args);
}
};
this._awaitWriteFinish(path, awf.stabilityThreshold, event, awfEmit);
return this;
}
if (event === EV.CHANGE) {
const isThrottled = !this._throttle(EV.CHANGE, path, 50);
if (isThrottled) return this;
}
if (
opts.alwaysStat &&
stats === undefined &&
(event === EV.ADD || event === EV.ADD_DIR || event === EV.CHANGE)
) {
const fullPath = opts.cwd ? sp.join(opts.cwd, path) : path;
let stats;
try {
stats = await stat(fullPath);
} catch (err) {
// do nothing
}
// Suppress event when fs_stat fails, to avoid sending undefined 'stat'
if (!stats || this.closed) return;
args.push(stats);
}
this.emitWithAll(event, args);
return this;
}
/**
* Common handler for errors
* @returns The error if defined, otherwise the value of the FSWatcher instance's `closed` flag
*/
_handleError(error: Error): Error | boolean {
const code = error && (error as Error & { code: string }).code;
if (
error &&
code !== 'ENOENT' &&
code !== 'ENOTDIR' &&
(!this.options.ignorePermissionErrors || (code !== 'EPERM' && code !== 'EACCES'))
) {
this.emit(EV.ERROR, error);
}
return error || this.closed;
}
/**
* Helper utility for throttling
* @param actionType type being throttled
* @param path being acted upon
* @param timeout duration of time to suppress duplicate actions
* @returns tracking object or false if action should be suppressed
*/
_throttle(actionType: ThrottleType, path: Path, timeout: number): Throttler | false {
if (!this._throttled.has(actionType)) {
this._throttled.set(actionType, new Map());
}
const action = this._throttled.get(actionType);
if (!action) throw new Error('invalid throttle');
const actionPath = action.get(path);
if (actionPath) {
actionPath.count++;
return false;
}
// eslint-disable-next-line prefer-const
let timeoutObject: NodeJS.Timeout;
const clear = () => {
const item = action.get(path);
const count = item ? item.count : 0;
action.delete(path);
clearTimeout(timeoutObject);
if (item) clearTimeout(item.timeoutObject);
return count;
};
timeoutObject = setTimeout(clear, timeout);
const thr = { timeoutObject, clear, count: 0 };
action.set(path, thr);
return thr;
}
_incrReadyCount(): number {
return this._readyCount++;
}
/**
* Awaits write operation to finish.
* Polls a newly created file for size variations. When files size does not change for 'threshold' milliseconds calls callback.
* @param path being acted upon
* @param threshold Time in milliseconds a file size must be fixed before acknowledging write OP is finished
* @param event
* @param awfEmit Callback to be called when ready for event to be emitted.
*/
_awaitWriteFinish(
path: Path,
threshold: number,
event: EventName,
awfEmit: (err?: Error, stat?: Stats) => void
): void {
const awf = this.options.awaitWriteFinish;
if (typeof awf !== 'object') return;
const pollInterval = awf.pollInterval as unknown as number;
let timeoutHandler: NodeJS.Timeout;
let fullPath = path;
if (this.options.cwd && !sp.isAbsolute(path)) {
fullPath = sp.join(this.options.cwd, path);
}
const now = new Date();
const writes = this._pendingWrites;
function awaitWriteFinishFn(prevStat?: Stats): void {
statcb(fullPath, (err, curStat) => {
if (err || !writes.has(path)) {
if (err && err.code !== 'ENOENT') awfEmit(err);
return;
}
const now = Number(new Date());
if (prevStat && curStat.size !== prevStat.size) {
writes.get(path).lastChange = now;
}
const pw = writes.get(path);
const df = now - pw.lastChange;
if (df >= threshold) {
writes.delete(path);
awfEmit(undefined, curStat);
} else {
timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval, curStat);
}
});
}
if (!writes.has(path)) {
writes.set(path, {
lastChange: now,
cancelWait: () => {
writes.delete(path);
clearTimeout(timeoutHandler);
return event;
},
});
timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval);
}
}
/**
* Determines whether user has asked to ignore this path.
*/
_isIgnored(path: Path, stats?: Stats): boolean {
if (this.options.atomic && DOT_RE.test(path)) return true;
if (!this._userIgnored) {
const { cwd } = this.options;
const ign = this.options.ignored;
const ignored = (ign || []).map(normalizeIgnored(cwd));
const ignoredPaths = [...this._ignoredPaths];
const list: Matcher[] = [...ignoredPaths.map(normalizeIgnored(cwd)), ...ignored];
this._userIgnored = anymatch(list, undefined);
}
return this._userIgnored(path, stats);
}
_isntIgnored(path: Path, stat?: Stats): boolean {
return !this._isIgnored(path, stat);
}
/**
* Provides a set of common helpers and properties relating to symlink handling.
* @param path file or directory pattern being watched
*/
_getWatchHelpers(path: Path): WatchHelper {
return new WatchHelper(path, this.options.followSymlinks, this);
}
// Directory helpers
// -----------------
/**
* Provides directory tracking objects
* @param directory path of the directory
*/
_getWatchedDir(directory: string): DirEntry {
const dir = sp.resolve(directory);
if (!this._watched.has(dir)) this._watched.set(dir, new DirEntry(dir, this._boundRemove));
return this._watched.get(dir)!;
}
// File helpers
// ------------
/**
* Check for read permissions: https://stackoverflow.com/a/11781404/1358405
*/
_hasReadPermissions(stats: Stats): boolean {
if (this.options.ignorePermissionErrors) return true;
return Boolean(Number(stats.mode) & 0o400);
}
/**
* Handles emitting unlink events for
* files and directories, and via recursion, for
* files and directories within directories that are unlinked
* @param directory within which the following item is located
* @param item base path of item/directory
*/
_remove(directory: string, item: string, isDirectory?: boolean): void {
// if what is being deleted is a directory, get that directory's paths
// for recursive deleting and cleaning of watched object
// if it is not a directory, nestedDirectoryChildren will be empty array
const path = sp.join(directory, item);
const fullPath = sp.resolve(path);
isDirectory =
isDirectory != null ? isDirectory : this._watched.has(path) || this._watched.has(fullPath);
// prevent duplicate handling in case of arriving here nearly simultaneously
// via multiple paths (such as _handleFile and _handleDir)
if (!this._throttle('remove', path, 100)) return;
// if the only watched file is removed, watch for its return
if (!isDirectory && this._watched.size === 1) {
this.add(directory, item, true);
}
// This will create a new entry in the watched object in either case
// so we got to do the directory check beforehand
const wp = this._getWatchedDir(path);
const nestedDirectoryChildren = wp.getChildren();
// Recursively remove children directories / files.
nestedDirectoryChildren.forEach((nested) => this._remove(path, nested));
// Check if item was on the watched list and remove it
const parent = this._getWatchedDir(directory);
const wasTracked = parent.has(item);
parent.remove(item);
// Fixes issue #1042 -> Relative paths were detected and added as symlinks
// (https://github.com/paulmillr/chokidar/blob/e1753ddbc9571bdc33b4a4af172d52cb6e611c10/lib/nodefs-handler.js#L612),
// but never removed from the map in case the path was deleted.
// This leads to an incorrect state if the path was recreated:
// https://github.com/paulmillr/chokidar/blob/e1753ddbc9571bdc33b4a4af172d52cb6e611c10/lib/nodefs-handler.js#L553
if (this._symlinkPaths.has(fullPath)) {
this._symlinkPaths.delete(fullPath);
}
// If we wait for this file to be fully written, cancel the wait.
let relPath = path;
if (this.options.cwd) relPath = sp.relative(this.options.cwd, path);
if (this.options.awaitWriteFinish && this._pendingWrites.has(relPath)) {
const event = this._pendingWrites.get(relPath).cancelWait();
if (event === EV.ADD) return;
}
// The Entry will either be a directory that just got removed
// or a bogus entry to a file, in either case we have to remove it
this._watched.delete(path);
this._watched.delete(fullPath);
const eventName: EventName = isDirectory ? EV.UNLINK_DIR : EV.UNLINK;
if (wasTracked && !this._isIgnored(path)) this._emit(eventName, path);
// Avoid conflicts if we later create another file with the same name
this._closePath(path);
}
/**
* Closes all watchers for a path
*/
_closePath(path: Path): void {
this._closeFile(path);
const dir = sp.dirname(path);
this._getWatchedDir(dir).remove(sp.basename(path));
}
/**
* Closes only file-specific watchers
*/
_closeFile(path: Path): void {
const closers = this._closers.get(path);
if (!closers) return;
closers.forEach((closer) => closer());
this._closers.delete(path);
}
_addPathCloser(path: Path, closer: () => void): void {
if (!closer) return;
let list = this._closers.get(path);
if (!list) {
list = [];
this._closers.set(path, list);
}
list.push(closer);
}
_readdirp(root: Path, opts?: Partial<ReaddirpOptions>): ReaddirpStream | undefined {
if (this.closed) return;
const options = { type: EV.ALL, alwaysStat: true, lstat: true, ...opts, depth: 0 };
let stream: ReaddirpStream | undefined = readdirp(root, options);
this._streams.add(stream);
stream.once(STR_CLOSE, () => {
stream = undefined;
});
stream.once(STR_END, () => {
if (stream) {
this._streams.delete(stream);
stream = undefined;
}
});
return stream;
}
}
/**
* Instantiates watcher with paths to be tracked.
* @param paths file / directory paths
* @param options opts, such as `atomic`, `awaitWriteFinish`, `ignored`, and others
* @returns an instance of FSWatcher for chaining.
* @example
* const watcher = watch('.').on('all', (event, path) => { console.log(event, path); });
* watch('.', { atomic: true, awaitWriteFinish: true, ignored: (f, stats) => stats?.isFile() && !f.endsWith('.js') })
*/
export function watch(paths: string | string[], options: ChokidarOptions = {}): FSWatcher {
const watcher = new FSWatcher(options);
watcher.add(paths);
return watcher;
}
export default { watch: watch as typeof watch, FSWatcher: FSWatcher as typeof FSWatcher };
================================================
FILE: tsconfig.json
================================================
{
"extends": "@paulmillr/jsbt/tsconfig.json",
"compilerOptions": {
"baseUrl": ".",
"outDir": ".",
"module": "node16",
"moduleResolution": "node16",
"allowSyntheticDefaultImports": true,
"noImplicitReturns": false,
"sourceMap": false,
"declarationMap": false
},
"include": [
"src"
],
"exclude": [
"node_modules"
]
}
gitextract_tssteiwg/ ├── .github/ │ ├── ISSUE_TEMPLATE/ │ │ └── bug_report.md │ ├── funding.yml │ └── workflows/ │ ├── release.yml │ └── test-js.yml ├── .gitignore ├── .prettierrc.json ├── LICENSE ├── README.md ├── example.js ├── package.json ├── src/ │ ├── handler.ts │ ├── index.test.ts │ └── index.ts └── tsconfig.json
SYMBOL INDEX (108 symbols across 3 files)
FILE: src/handler.ts
type Path (line 9) | type Path = string;
constant STR_DATA (line 11) | const STR_DATA = 'data';
constant STR_END (line 12) | const STR_END = 'end';
constant STR_CLOSE (line 13) | const STR_CLOSE = 'close';
constant EVENTS (line 24) | const EVENTS = {
type EventName (line 35) | type EventName = (typeof EVENTS)[keyof typeof EVENTS];
constant THROTTLE_MODE_WATCH (line 38) | const THROTTLE_MODE_WATCH = 'watch';
constant KEY_LISTENERS (line 42) | const KEY_LISTENERS = 'listeners';
constant KEY_ERR (line 43) | const KEY_ERR = 'errHandlers';
constant KEY_RAW (line 44) | const KEY_RAW = 'rawEmitters';
constant HANDLER_KEYS (line 45) | const HANDLER_KEYS = [KEY_LISTENERS, KEY_ERR, KEY_RAW];
type FsWatchContainer (line 127) | type FsWatchContainer = {
function createFsWatchInstance (line 146) | function createFsWatchInstance(
type WatchHandlers (line 195) | interface WatchHandlers {
class NodeFsHandler (line 364) | class NodeFsHandler {
method constructor (line 367) | constructor(fsW: FSWatcher) {
method _watchWithNodeFs (line 378) | _watchWithNodeFs(
method _handleFile (line 415) | _handleFile(file: Path, stats: Stats, initialAdd: boolean): (() => voi...
method _handleSymlink (line 483) | async _handleSymlink(
method _handleRead (line 530) | _handleRead(
method _handleDir (line 631) | async _handleDir(
method _addToNodeFs (line 678) | async _addToNodeFs(
FILE: src/index.test.ts
constant TEST_TIMEOUT (line 25) | const TEST_TIMEOUT = 32000;
constant FIXTURES_PATH (line 27) | const FIXTURES_PATH = sp.join(tmpdir(), 'chokidar-' + time());
constant WATCHERS (line 28) | const WATCHERS: chokidar.FSWatcher[] = [];
constant USE_SLOW_DELAY (line 31) | let USE_SLOW_DELAY: number | undefined;
function time (line 33) | function time() {
function rmr (line 37) | function rmr(dir: string) {
function mkdir (line 40) | function mkdir(dir: string, opts = {}) {
function calledWith (line 44) | function calledWith<TArgs extends unknown[], TReturn>(
function getCallsWith (line 51) | function getCallsWith<TArgs extends unknown[], TReturn>(
function alwaysCalledWith (line 60) | function alwaysCalledWith<TArgs extends unknown[], TReturn>(
function delay (line 118) | async function delay(delayTime?: number) {
function dpath (line 126) | function dpath(subPath: string) {
function gpath (line 131) | function gpath(subPath: string) {
function cwatch (line 137) | function cwatch(
function isSpyReady (line 146) | function isSpyReady(spy: Spy | [spy: Spy, callCount: number, args?: unkn...
function waitFor (line 159) | function waitFor(spies: Array<Spy | [spy: Spy, callCount: number, args?:...
function waitForEvents (line 176) | function waitForEvents(watcher: chokidar.FSWatcher, count: number) {
function rmSlashes (line 2028) | function rmSlashes(str: string) {
function main (line 2081) | async function main() {
FILE: src/index.ts
type AWF (line 21) | type AWF = {
type BasicOpts (line 26) | type BasicOpts = {
type Throttler (line 45) | type Throttler = {
type ChokidarOptions (line 51) | type ChokidarOptions = Partial<
type FSWInstanceOptions (line 58) | type FSWInstanceOptions = BasicOpts & {
type ThrottleType (line 63) | type ThrottleType = 'readdir' | 'watch' | 'add' | 'remove' | 'change';
type EmitArgs (line 64) | type EmitArgs = [path: Path, stats?: Stats];
type EmitErrorArgs (line 65) | type EmitErrorArgs = [error: Error, stats?: Stats];
type EmitArgsWithName (line 66) | type EmitArgsWithName = [event: EventName, ...EmitArgs];
type MatchFunction (line 67) | type MatchFunction = (val: string, stats?: Stats) => boolean;
type MatcherObject (line 68) | interface MatcherObject {
type Matcher (line 72) | type Matcher = string | RegExp | MatchFunction | MatcherObject;
constant SLASH (line 74) | const SLASH = '/';
constant SLASH_SLASH (line 75) | const SLASH_SLASH = '//';
constant ONE_DOT (line 76) | const ONE_DOT = '.';
constant TWO_DOTS (line 77) | const TWO_DOTS = '..';
constant STRING_TYPE (line 78) | const STRING_TYPE = 'string';
constant BACK_SLASH_RE (line 79) | const BACK_SLASH_RE = /\\/g;
constant DOUBLE_SLASH_RE (line 80) | const DOUBLE_SLASH_RE = /\/\//g;
constant DOT_RE (line 81) | const DOT_RE = /\..*\.(sw[px])$|~$|\.subl.*\.tmp/;
constant REPLACER_RE (line 82) | const REPLACER_RE = /^\.[/\\]/;
function arrify (line 84) | function arrify<T>(item: T | T[]): T[] {
function createPattern (line 91) | function createPattern(matcher: Matcher): MatchFunction {
function normalizePath (line 111) | function normalizePath(path: Path): Path {
function matchPatterns (line 122) | function matchPatterns(patterns: MatchFunction[], testString: string, st...
function anymatch (line 137) | function anymatch(matchers: Matcher[], testString: string | undefined): ...
constant EMPTY_SET (line 200) | const EMPTY_SET = Object.freeze(new Set<string>());
class DirEntry (line 204) | class DirEntry {
method constructor (line 209) | constructor(dir: Path, removeWatcher: (dir: string, base: string) => v...
method add (line 215) | add(item: string): void {
method remove (line 221) | async remove(item: string): Promise<void> {
method has (line 237) | has(item: string): boolean | undefined {
method getChildren (line 243) | getChildren(): string[] {
method dispose (line 249) | dispose(): void {
constant STAT_METHOD_F (line 258) | const STAT_METHOD_F = 'stat';
constant STAT_METHOD_L (line 259) | const STAT_METHOD_L = 'lstat';
class WatchHelper (line 260) | class WatchHelper {
method constructor (line 269) | constructor(path: string, follow: boolean, fsw: FSWatcher) {
method entryPath (line 283) | entryPath(entry: EntryInfo): Path {
method filterPath (line 287) | filterPath(entry: EntryInfo): boolean {
method filterDir (line 295) | filterDir(entry: EntryInfo): boolean {
type FSWatcherEventMap (line 300) | interface FSWatcherEventMap {
class FSWatcher (line 320) | class FSWatcher extends EventEmitter<FSWatcherEventMap> {
method constructor (line 344) | constructor(_opts: ChokidarOptions = {}) {
method _addIgnoredPath (line 417) | _addIgnoredPath(matcher: Matcher): void {
method _removeIgnoredPath (line 434) | _removeIgnoredPath(matcher: Matcher): void {
method add (line 456) | add(paths_: Path | Path[], _origAdd?: string, _internal?: boolean): FS...
method unwatch (line 503) | unwatch(paths_: Path | Path[]): FSWatcher {
method close (line 536) | close(): Promise<void> {
method getWatched (line 573) | getWatched(): Record<string, string[]> {
method emitWithAll (line 583) | emitWithAll(event: EventName, args: EmitArgs): void {
method _emit (line 599) | async _emit(event: EventName, path: Path, stats?: Stats): Promise<this...
method _handleError (line 687) | _handleError(error: Error): Error | boolean {
method _throttle (line 707) | _throttle(actionType: ThrottleType, path: Path, timeout: number): Thro...
method _incrReadyCount (line 737) | _incrReadyCount(): number {
method _awaitWriteFinish (line 749) | _awaitWriteFinish(
method _isIgnored (line 808) | _isIgnored(path: Path, stats?: Stats): boolean {
method _isntIgnored (line 823) | _isntIgnored(path: Path, stat?: Stats): boolean {
method _getWatchHelpers (line 831) | _getWatchHelpers(path: Path): WatchHelper {
method _getWatchedDir (line 842) | _getWatchedDir(directory: string): DirEntry {
method _hasReadPermissions (line 854) | _hasReadPermissions(stats: Stats): boolean {
method _remove (line 866) | _remove(directory: string, item: string, isDirectory?: boolean): void {
method _closePath (line 928) | _closePath(path: Path): void {
method _closeFile (line 937) | _closeFile(path: Path): void {
method _addPathCloser (line 944) | _addPathCloser(path: Path, closer: () => void): void {
method _readdirp (line 954) | _readdirp(root: Path, opts?: Partial<ReaddirpOptions>): ReaddirpStream...
function watch (line 981) | function watch(paths: string | string[], options: ChokidarOptions = {}):...
Condensed preview — 14 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (158K chars).
[
{
"path": ".github/ISSUE_TEMPLATE/bug_report.md",
"chars": 1294,
"preview": "---\nname: Bug report\nabout: Create a report to help us improve\n\n---\n\n**Describe the bug**\n\nA clear and concise descripti"
},
{
"path": ".github/funding.yml",
"chars": 58,
"preview": "github: paulmillr\n# custom: https://paulmillr.com/funding/"
},
{
"path": ".github/workflows/release.yml",
"chars": 286,
"preview": "name: Publish release\non:\n release:\n types: [created]\njobs:\n release-js:\n name: 'jsbt v0.4.5' # Should match com"
},
{
"path": ".github/workflows/test-js.yml",
"chars": 221,
"preview": "name: Run TS tests\non:\n - push\n - pull_request\njobs:\n test-ts:\n name: 'jsbt v0.4.5' # Should match commit below\n "
},
{
"path": ".gitignore",
"chars": 128,
"preview": "*.bak\n*.log\n/coverage/\n/node_modules/\n/test-fixtures/\n/*.d.ts\n/*.d.mts\n/*.map\n/index.js\n/handler.js\n/esm\n/*.test.js\n/*.t"
},
{
"path": ".prettierrc.json",
"chars": 73,
"preview": "{\n \"printWidth\": 100,\n \"singleQuote\": true,\n \"trailingComma\": \"es5\"\n}\n"
},
{
"path": "LICENSE",
"chars": 1116,
"preview": "The MIT License (MIT)\n\nCopyright (c) 2012 Paul Miller (https://paulmillr.com), Elan Shanker\n\nPermission is hereby grante"
},
{
"path": "README.md",
"chars": 13324,
"preview": "# Chokidar [](https://github.com/paulmillr/chokidar)\n\nMin"
},
{
"path": "example.js",
"chars": 352,
"preview": "global.watcher = require('./index.js').default.watch('.', {\n ignored: /node_modules|\\.git/,\n persistent: true,\n // fo"
},
{
"path": "package.json",
"chars": 1346,
"preview": "{\n \"name\": \"chokidar\",\n \"description\": \"Minimal and efficient cross-platform file watching library\",\n \"version\": \"5.0"
},
{
"path": "src/handler.ts",
"chars": 24661,
"preview": "import type { FSWatcher as NativeFsWatcher, Stats, WatchEventType, WatchListener } from 'node:fs';\nimport { watch as fs_"
},
{
"path": "src/index.test.ts",
"chars": 79776,
"preview": "import { afterEach, beforeEach, describe, it } from '@paulmillr/jsbt/test.js';\nimport { deepEqual, equal, ok, throws } f"
},
{
"path": "src/index.ts",
"chars": 30237,
"preview": "/*! chokidar - MIT License (c) 2012 Paul Miller (paulmillr.com) */\nimport type { Stats } from 'node:fs';\nimport { EventE"
},
{
"path": "tsconfig.json",
"chars": 369,
"preview": "{\n \"extends\": \"@paulmillr/jsbt/tsconfig.json\",\n \"compilerOptions\": {\n \"baseUrl\": \".\",\n \"outDir\": \".\",\n \"modul"
}
]
About this extraction
This page contains the full source code of the paulmillr/chokidar GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 14 files (149.6 KB), approximately 40.2k tokens, and a symbol index with 108 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.