Chokidar Cheatsheet

Posted Tuesday, March 8, 2022 by Sri. Tagged MEMO, CHEATSHEET
EDITING PHASE:gathering info...

from https://github.com/paulmillr/chokidar

Chokidar Initialization

// Initialize watcher.
const watcher = chokidar.watch('file, dir, glob, or array', {
ignored: /(^|[\/\\])\../, // ignore dotfiles
persistent: true
});
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/Remove/Stop Watches

watcher.add('new-file');
watcher.add(['new-file-2', 'new-file-3', '**/other-file*']);

var watchedPaths = watcher.getWatched();

await watcher.unwatch('new-file*');

// Stop watching. The method is async!
watcher.close().then(() => console.log('closed'));

Extended File Information

// '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}`);
});

Chokidar Events

const watcher = chokidar.watch('file, dir, glob, or array', {
ignored: /(^|[\/\\])\../, // ignore dotfiles
persistent: true
});
watcher
.on('add', path => log(`file ${path} added`))
.on('change', path => log(`file ${path} changed`))
.on('unlink', path => log(`file ${path} removed`));
watcher
.on('addDir', path => log(`dir ${path} added`))
.on('unlinkDir', path => log(`dir ${path} removed`))
watcher
.on('error', error => { ... })
.on('ready', () => log('initial scan complete. ready'))
.on('raw', (event, path, details) => { /* internal */ });

Chokidar Options

See Chokidar API for descriptions.

  persistent: true,
//
ignored: '*.txt',
ignoreInitial: false,
followSymlinks: true,
cwd: '.',
disableGlobbing: false,
//
usePolling: false,
interval: 100,
binaryInterval: 300,
alwaysStat: false,
depth: 99,
awaitWriteFinish: {
stabilityThreshold: 2000,
pollInterval: 100
},
//
ignorePermissionErrors: false,
atomic: true // or a custom 'atomicity delay', in milliseconds (default 100)
});