Chokidar An In-depth Guide to File Watching in Node.js

Introduction to Chokidar

Chokidar is a highly efficient and fast file watching library for Node.js applications. It is ideal for tracking changes in the filesystem and is more efficient than the built-in fs.watch and fs.watchFile modules. Chokidar uses native OS events to receive filesystem notifications, providing a robust and scalable solution for file watching.

Installation

  npm install chokidar

Basic Usage

  const chokidar = require('chokidar');

  // Initialize watcher.
  const watcher = chokidar.watch('file, dir, or glob', {
    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`));

  // More possible 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);
    });

Advanced Configuration

Chokidar provides a range of options to cater to advanced use cases.

  const watcher = chokidar.watch('file, dir, or glob', {
    persistent: true,
    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,
  });

API Examples

watch

  const watcher = chokidar.watch('file, dir, or glob', [options]);

on

  watcher.on('event', path => {
    console.log(`File ${path} has been added/changed/removed`);
  });

close

  watcher.close().then(() => console.log('Watcher closed'));

getWatched

  console.log(watcher.getWatched());

App Example

Below is a simple example of a Node.js application using Chokidar to watch a directory for changes.

  const chokidar = require('chokidar');

  const watcher = chokidar.watch('test-dir', {
    ignored: /(^|[\/\\])\../,
    persistent: true
  });

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

  setTimeout(() => {
    watcher.close().then(() => console.log('Watcher closed'));
  }, 60000);

By integrating Chokidar into your Node.js application, you can efficiently monitor and respond to changes in your filesystem, making it a powerful tool for various development and production scenarios.

Hash: 9365374aff724ca31cca071cb8ee294cc98603fcd07ce9454dd396ab9c66ae96

Leave a Reply

Your email address will not be published. Required fields are marked *