Introduction to Chokidar
Chokidar is a fast and efficient file system watcher library for Node.js. It uses native APIs to provide accurate and reliable file system events, making it a pivotal tool for developers working with file operations. This article will explore the ins and outs of Chokidar’s API with illustrative examples. Let’s dive in!
Installing Chokidar
npm install chokidar
Basic Usage
Watch a directory for changes:
const chokidar = require('chokidar');
// Initialize watcher const watcher = chokidar.watch('path/to/dir', {
ignored: /(^|[\/\\])\../, // ignore dotfiles
persistent: true
});
// Add event listeners watcher
.on('add', path => console.log(`File ${path} has been added`))
.on('change', path => console.log(`File ${path} has been changed`))
.on('unlink', path => console.log(`File ${path} has been removed`));
API Explanations
.on(event, listener)
Listen for an event. Supported events include add
, change
, unlink
, addDir
, unlinkDir
, and several others:
watcher.on('addDir', path => console.log(`Directory ${path} has been added`)); watcher.on('unlinkDir', path => console.log(`Directory ${path} has been removed`));
.add(paths)
Watch new paths:
watcher.add('new/path/to/file');
.unwatch(paths)
Stop watching paths:
watcher.unwatch('path/to/file');
.close()
Close the watcher:
watcher.close().then(() => console.log('Watcher closed'));
.getWatched()
Returns an object that represents all the currently watched paths:
console.log(watcher.getWatched());
.isPaused()
Check if the watcher is paused:
console.log(watcher.isPaused());
Simple Application Example
Here’s a simple application that uses chokidar to automate tasks when files are modified:
const chokidar = require('chokidar'); const { exec } = require('child_process');
const watcher = chokidar.watch('src', {
ignored: /(^|[\/\\])\../, // ignore dotfiles
persistent: true
});
watcher
.on('change', path => {
console.log(`File ${path} has been changed`);
exec('npm test', (err, stdout, stderr) => {
if (err) {
console.error(`exec error: ${err}`);
return;
}
console.log(`stdout: ${stdout}`);
console.error(`stderr: ${stderr}`);
});
});
console.log('Watching for file changes...');
Conclusion
Chokidar makes it incredibly easy to watch for file system changes and execute tasks when modifications are detected. It is a vital tool for developers who need a reliable method to monitor and respond to changes in files and directories.
Hash: 9365374aff724ca31cca071cb8ee294cc98603fcd07ce9454dd396ab9c66ae96