yuanchuan / node-watch

A wrapper and enhancements for fs.watch
https://npm.im/node-watch
MIT License
340 stars 44 forks source link
fs-watch watch-files watcher wrapper

node-watch Status

A wrapper and enhancements for fs.watch.

NPM

Installation

npm install node-watch

Example

var watch = require('node-watch');

watch('file_or_dir', { recursive: true }, function(evt, name) {
  console.log('%s changed.', name);
});

Now it's fast to watch deep directories on macOS and Windows, since the recursive option is natively supported except on Linux.

// watch the whole disk
watch('/', { recursive: true }, console.log);

Why?

Options

The usage and options of node-watch are compatible with fs.watch.

Extra options

Events

The events provided by the callback function is either update or remove, which is less confusing to fs.watch's rename or change.

watch('./', function(evt, name) {

  if (evt == 'update') {
    // on create or modify
  }

  if (evt == 'remove') {
    // on delete
  }

});

Watcher object

The watch function returns a fs.FSWatcher like object as the same as fs.watch (>= v0.4.0).

Watcher events

let watcher = watch('./', { recursive: true });

watcher.on('change', function(evt, name) {
  // callback
});

watcher.on('error', function(err) {
  // handle error
});

watcher.on('ready', function() {
  // the watcher is ready to respond to changes
});

Close

// close
watcher.close();

// is closed?
watcher.isClosed()

List of methods

Extra methods

Known issues

Windows, node < v4.2.5

MacOS, node 0.10.x

Misc

1. Watch multiple files or directories in one place

watch(['file1', 'file2'], console.log);

2. Customize watch command line tool

#!/usr/bin/env node

// https://github.com/nodejs/node-v0.x-archive/issues/3211
require('epipebomb')();

let watcher = require('node-watch')(
  process.argv[2] || './', { recursive: true }, console.log
);

process.on('SIGINT', watcher.close);

Monitoring chrome from disk:

$ watch / | grep -i chrome

3. Got ENOSPC error?

If you get ENOSPC error, but you actually have free disk space - it means that your OS watcher limit is too low and you probably want to recursively watch a big tree of files.

Follow this description to increase the limit: https://confluence.jetbrains.com/display/IDEADEV/Inotify+Watches+Limit

Alternatives

Contributors

Thanks goes to all wonderful people who have helped this project.

License

MIT

Copyright (c) 2012-2021 yuanchuan