Convert Figma logo to code with AI

mikeal logowatch

Utilities for watching file trees in node.js

1,275
141
1,275
60

Top Related Projects

10,813

Minimal and efficient cross-platform file watching library

1,156

:crystal_ball: A globbing fs.watch wrapper built from the best parts of other fine watch libs.

26,226

Monitor for any changes in your node.js application and automatically restart the server - perfect for development

Quick Overview

Mikeal/watch is a Node.js library that provides a simple and efficient way to watch for file system changes. It allows developers to monitor directories and files for modifications, additions, and deletions, making it useful for tasks such as live reloading, build processes, and file synchronization.

Pros

  • Easy to use with a straightforward API
  • Efficient file system watching with minimal resource usage
  • Cross-platform compatibility (works on Windows, macOS, and Linux)
  • Supports recursive directory watching

Cons

  • Limited documentation and examples
  • Not actively maintained (last update was several years ago)
  • May have compatibility issues with newer Node.js versions
  • Lacks some advanced features found in more recent file watching libraries

Code Examples

  1. Watch a single directory:
const watch = require('watch');

watch.createMonitor('/path/to/directory', function (monitor) {
  monitor.on("created", function (f, stat) {
    console.log('File created:', f);
  });
  monitor.on("changed", function (f, curr, prev) {
    console.log('File changed:', f);
  });
  monitor.on("removed", function (f, stat) {
    console.log('File removed:', f);
  });
});
  1. Watch a directory recursively:
const watch = require('watch');

watch.watchTree('/path/to/directory', function (f, curr, prev) {
  if (typeof f == "object" && prev === null && curr === null) {
    // Finished walking the tree
    console.log('Finished walking the directory tree');
  } else if (prev === null) {
    // f is a new file
    console.log('New file:', f);
  } else if (curr.nlink === 0) {
    // f was removed
    console.log('File removed:', f);
  } else {
    // f was changed
    console.log('File changed:', f);
  }
});
  1. Watch with options:
const watch = require('watch');

const options = {
  ignoreDotFiles: true,
  filter: function(f, stat) {
    return stat.isDirectory() || /\.js$/.test(f);
  }
};

watch.watchTree('/path/to/directory', options, function (f, curr, prev) {
  // Handle changes
});

Getting Started

To use mikeal/watch in your Node.js project:

  1. Install the package:

    npm install watch
    
  2. Require the module in your JavaScript file:

    const watch = require('watch');
    
  3. Start watching a directory:

    watch.createMonitor('/path/to/directory', function (monitor) {
      monitor.on("created", function (f, stat) {
        console.log('File created:', f);
      });
      // Add more event handlers as needed
    });
    

Competitor Comparisons

10,813

Minimal and efficient cross-platform file watching library

Pros of Chokidar

  • More actively maintained with frequent updates
  • Cross-platform compatibility, including better Windows support
  • Offers more advanced features like atomic writes and symlink following

Cons of Chokidar

  • Larger package size and more dependencies
  • Slightly more complex API, which may be overkill for simple use cases

Code Comparison

Watch:

var watch = require('watch');
watch.createMonitor('/home/mikeal', function (monitor) {
  monitor.on("created", function (f, stat) {
    // Handle new files
  })
})

Chokidar:

const chokidar = require('chokidar');
const watcher = chokidar.watch('/home/mikeal', {
  persistent: true
});
watcher.on('add', (path) => {
  // Handle new files
});

Both libraries provide file system watching capabilities, but Chokidar offers more robust and flexible options. Watch is simpler and lighter, which may be preferable for basic use cases. Chokidar's API is more extensive, allowing for fine-tuned control over watching behavior, while Watch provides a more straightforward approach. The choice between the two depends on the specific requirements of your project, with Chokidar being better suited for complex scenarios and Watch for simpler applications.

1,156

:crystal_ball: A globbing fs.watch wrapper built from the best parts of other fine watch libs.

Pros of Gaze

  • More actively maintained with recent updates
  • Supports globbing patterns for more flexible file watching
  • Provides a more extensive API with additional events and options

Cons of Gaze

  • Larger package size and more dependencies
  • Slightly more complex setup and configuration
  • May have higher resource usage for large file systems

Code Comparison

Watch:

var watch = require('watch');
watch.createMonitor('/path/to/watch', function (monitor) {
  monitor.on("created", function (f, stat) {
    // Handle file creation
  });
});

Gaze:

var gaze = require('gaze');
gaze('**/*', function(err, watcher) {
  this.on('added', function(filepath) {
    // Handle file addition
  });
});

Both Watch and Gaze are file watching libraries for Node.js, but they differ in their approach and features. Watch is simpler and more lightweight, while Gaze offers more advanced functionality and flexibility. The choice between them depends on the specific requirements of your project, such as the need for globbing patterns, the size of the file system being watched, and the desired level of control over the watching process.

26,226

Monitor for any changes in your node.js application and automatically restart the server - perfect for development

Pros of nodemon

  • More actively maintained with frequent updates
  • Supports automatic restarting of Node.js applications
  • Offers extensive configuration options and CLI flags

Cons of nodemon

  • Larger package size and more dependencies
  • May have a steeper learning curve for beginners

Code Comparison

nodemon:

nodemon({
  script: 'app.js',
  ext: 'js json',
  ignore: ['ignored.js'],
  execMap: {
    js: 'node --harmony'
  }
});

watch:

watch.watchTree('.', function (f, curr, prev) {
  console.log('File changed');
});

Key Differences

  • nodemon is specifically designed for Node.js development, while watch is a more general-purpose file watching utility
  • nodemon provides built-in support for restarting Node.js applications, whereas watch requires additional setup for this functionality
  • watch has a simpler API and is easier to integrate into custom build processes

Use Cases

  • nodemon: Ideal for Node.js developers who want an out-of-the-box solution for auto-restarting applications during development
  • watch: Better suited for developers who need a lightweight file watching utility for custom build processes or non-Node.js projects

Community and Ecosystem

nodemon has a larger user base and more third-party integrations, while watch is more focused on providing a simple, core functionality for file watching.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

watch -- Utilities for watching file trees in node.js

Install

  npm install watch

Purpose

The intention of this module is provide tools that make managing the watching of file & directory trees easier.

watch.watchTree(root, [options,] callback)

The first argument is the directory root you want to watch.

The options object is passed to fs.watchFile but can also be used to provide two additional watchTree specific options:

  • 'ignoreDotFiles' - When true this option means that when the file tree is walked it will ignore files that being with "."
  • 'filter' - You can use this option to provide a function that returns true or false for each file and directory to decide whether or not that file/directory is included in the watcher.
  • 'interval' - Specifies the interval duration in seconds, the time period between polling for file changes.
  • 'ignoreUnreadableDir' - When true, this options means that when a file can't be read, this file is silently skipped.
  • 'ignoreNotPermitted' - When true, this options means that when a file can't be read due to permission issues, this file is silently skipped.
  • 'ignoreDirectoryPattern' - When a regex pattern is set, e.g. /node_modules/, these directories are silently skipped.

The callback takes 3 arguments. The first is the file that was modified. The second is the current stat object for that file and the third is the previous stat object.

When a file is new the previous stat object is null.

When watchTree is finished walking the tree and adding all the listeners it passes the file hash (keys are the file/directory names and the values are the current stat objects) as the first argument and null as both the previous and current stat object arguments.

  watch.watchTree('/home/mikeal', function (f, curr, prev) {
    if (typeof f == "object" && prev === null && curr === null) {
      // Finished walking the tree
    } else if (prev === null) {
      // f is a new file
    } else if (curr.nlink === 0) {
      // f was removed
    } else {
      // f was changed
    }
  })

watch.unwatchTree(root)

Unwatch a previously watched directory root using watch.watchTree.

watch.createMonitor(root, [options,] callback)

This function creates an EventEmitter that gives notifications for different changes that happen to the file and directory tree under the given root argument.

The options object is passed to watch.watchTree.

The callback receives the monitor object.

The monitor object contains a property, files, which is a hash of files and directories as keys with the current stat object as the value.

The monitor has the following events.

  • 'created' - New file has been created. Two arguments, the filename and the stat object.
  • 'removed' - A file has been moved or deleted. Two arguments, the filename and the stat object for the fd.
  • 'changed' - A file has been changed. Three arguments, the filename, the current stat object, and the previous stat object.

The monitor can be stopped using .stop (calls unwatchTree).

  var watch = require('watch')
  watch.createMonitor('/home/mikeal', function (monitor) {
    monitor.files['/home/mikeal/.zshrc'] // Stat object for my zshrc.
    monitor.on("created", function (f, stat) {
      // Handle new files
    })
    monitor.on("changed", function (f, curr, prev) {
      // Handle file changes
    })
    monitor.on("removed", function (f, stat) {
      // Handle removed files
    })
    monitor.stop(); // Stop watching
  })

CLI

This module includes a simple command line interface, which you can install with npm install watch -g.

Usage: watch <command> [...directory] [OPTIONS]

OPTIONS:
    --wait=<seconds>
        Duration, in seconds, that watching will be disabled
        after running <command>. Setting this option will
        throttle calls to <command> for the specified duration.

    --filter=<file>
        Path to a require-able .js file that exports a filter
        function to be passed to watchTreeOptions.filter.
        Path is resolved relative to process.cwd().

    --interval=<seconds>
        Specifies the interval duration in seconds, the time period between polling for file changes.

    --ignoreDotFiles, -d
        Ignores dot or hidden files in the watch [directory].

     --ignoreUnreadable, -u
        Silently ignores files that cannot be read within the
        watch [directory].

     --ignoreDirectoryPattern=<regexp>, -p
        Silently skips directories that match the regular
        expression.

It will watch the given directories (defaults to the current working directory) with watchTree and run the given command every time a file changes.

Examples

As stated above the pattern is:

watch <command> [...directory] [OPTIONS]

To run the watch command in the terminal you have to write the following:

watch 'npm run test -s' directory

As the command has to be written in quotation marks Windows users may need to use double quotes rather than single quotes

watch "npm run test -s" directory

Note: Because Windows users may need to use double quotes rather than single quotes they need to escape the them in npm scripts

"scripts": {
    "watch:osx": "watch 'npm run test -s' source"
    "watch:windows": "watch \"npm run test -s\" source",
}

Contributing

Releasing

On the latest clean master:

npm run release:major
npm run release:minor
npm run release:patch

NPM DownloadsLast 30 Days