Introduction to Chokidar: Efficient File Watching for Node.js
Chokidar is a highly efficient and powerful file watching library for Node.js that simplifies the process of monitoring file system changes. Its robust API enables developers to handle various file system events seamlessly. In this article, we’ll explore the key features and APIs Chokidar offers, along with practical examples to help you integrate this library into your applications effectively.
Getting Started with Chokidar
To use Chokidar in your project, first install it using npm:
npm install chokidar
Basic Usage
Here’s a simple example of using Chokidar to watch for changes in a directory:
const chokidar = require('chokidar'); // Initialize watcher const watcher = chokidar.watch('./dir-to-watch', { ignored: /^\./, 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`));
Advanced API Usage
Watching Specific Files and Directories
Chokidar allows you to target specific files and directories:
const watcher = chokidar.watch(['file1.txt', 'dir2'], { persistent: true });
Handling Events
Chokidar provides several event listeners to handle file system events:
watcher .on('addDir', path => console.log(`Directory ${path} has been added`)) .on('unlinkDir', path => console.log(`Directory ${path} has been removed`)) .on('error', error => console.log(`Watcher error: ${error}`)) .on('ready', () => console.log('Initial scan complete. Ready for changes')) .on('raw', (event, path, details) => { console.log('Raw event info:', event, path, details); });
Stopping the Watcher
To stop watching, you can use the close
method:
watcher.close().then(() => console.log('Watcher stopped'));
Practical Application Example
Let’s create a simple application that monitors a directory and logs changes to a file:
const fs = require('fs'); const chokidar = require('chokidar'); const logFile = './log.txt'; const log = msg => { fs.appendFile(logFile, msg + '\n', err => { if (err) throw err; }); }; const watcher = chokidar.watch('./dir-to-watch', { ignored: /^\./, 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`)) .on('error', error => log(`Watcher error: ${error}`)) .on('ready', () => log('Initial scan complete. Ready for changes'));
In this example, any changes detected in ./dir-to-watch
will be logged to log.txt
.
By leveraging the capabilities of Chokidar, you can efficiently monitor and respond to file system changes within your Node.js applications.
Hash: 9365374aff724ca31cca071cb8ee294cc98603fcd07ce9454dd396ab9c66ae96