• Stars
    star
    340
  • Rank 124,317 (Top 3 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 12 years ago
  • Updated 10 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A wrapper and enhancements for fs.watch

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?

  • Some editors will generate temporary files which will cause the callback function to be triggered multiple times.
  • The callback function will only be triggered once on watching a single file.
  • Missing an option to watch a directory recursively.
  • Recursive watch is not supported on Linux or in older versions of nodejs.
  • Keep it simple, stupid.

Options

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

  • persistent: Boolean (default true)
  • recursive: Boolean (default false)
  • encoding: String (default 'utf8')

Extra options

  • filter: RegExp | Function

    Return that matches the filter expression.

    // filter with regular expression
    watch('./', { filter: /\.json$/ });
    
    // filter with custom function
    watch('./', { filter: f => !/node_modules/.test(f) });

    Each file and directory will be passed to the filter to determine whether it will then be passed to the callback function. Like Array.filter does in JavaScript. There are three kinds of return values for filter function:

    • true: Will be passed to callback.
    • false: Will not be passed to callback.
    • skip: Same with false, and skip to watch all its subdirectories.

    On Linux, where the recursive option is not natively supported, it is more efficient to skip ignored directories by returning the skip flag:

    watch('./', {
      recursive: true,
      filter(f, skip) {
        // skip node_modules
        if (/\/node_modules/.test(f)) return skip;
        // skip .git folder
        if (/\.git/.test(f)) return skip;
        // only watch for js files
        return /\.js$/.test(f);
      }
    });

    If you prefer glob patterns you can use minimatch or picomatch together with filter:

    const pm = require('picomatch');
    let isMatch = pm('*.js');
    
    watch('./', {
      filter: f => isMatch(f)
    });
  • delay: Number (in ms, default 200)

    Delay time of the callback function.

    // log after 5 seconds
    watch('./', { delay: 5000 }, console.log);

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

  • .on
  • .once
  • .emit
  • .close
  • .listeners
  • .setMaxListeners
  • .getMaxListeners
Extra methods
  • .isClosed detect if the watcher is closed
  • .getWatchedPaths get all the watched paths

Known issues

Windows, node < v4.2.5

  • Failed to detect remove event
  • Failed to get deleted filename or directory name

MacOS, node 0.10.x

  • Will emit double event if the directory name is of one single character.

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

More Repositories

1

sveltekit-autoimport

Automatically detect and import components/modules for SvelteKit projects
JavaScript
230
star
2

game-of-life

A browser extension to play Conway's Game of Life on GitHub contribution board
JavaScript
209
star
3

talk

HTML
95
star
4

codepen-prefill

Create new pen from local HTML/JS/CSS files with ease
JavaScript
75
star
5

gradient-shapes

Shapes generated with CSS background gradients.
HTML
75
star
6

markdown-preview

Markdown preview made easy (with live update)
CSS
70
star
7

CSS-at

A collection of styleguides or approach to CSS at different companies
55
star
8

find

Find files or directories by name
JavaScript
47
star
9

css-shapes-patterns

CSS Shapes Patterns
HTML
37
star
10

match

Erlang-like pattern matching in JavaScript.
JavaScript
33
star
11

ikko-tanaka

Ikko Tanaka's graphic design in CSS
CSS
28
star
12

css-fractal

A proof of concept to show the elegance of css
HTML
27
star
13

svelte-pen

Create Svelte component demo quickly
JavaScript
11
star
14

style

Create stylesheets dynamically in javascript
JavaScript
10
star
15

intro-to-css-doodle

Presentation for the Groove Meetup
HTML
6
star
16

game-controller

Your mobile phone as a game controller
JavaScript
5
star
17

mock

Mock server for personal usage
JavaScript
5
star
18

jd

cd to path quickly
Go
5
star
19

FizzBuzzWhizz

FizzBuzzWhizz in css
JavaScript
5
star
20

redis-commands

Redis commands in javascript
JavaScript
4
star
21

html-tag-printer

A simple & small tool easily output HTML tags in php
PHP
4
star
22

brainfuck

A simple brainfuck interpreter
JavaScript
4
star
23

fractal-div

Fractals made out of divs
Haskell
4
star
24

tiny-template

A tiny template engine without using `eval` or `new Function`
JavaScript
3
star
25

cond

Lisp-like conditional statement for JSX
JavaScript
3
star
26

praxis

Practice makes perfect
JavaScript
3
star
27

whirling-rain

A Windows screensaver
C++
3
star
28

sveltekit-issues

JavaScript
2
star
29

browser-bugs

Browser bugs I found while experimenting
2
star
30

wallpapers

Picked wallpapers
2
star
31

postcss-polygon-shapes

Generate shapes using polygon()
JavaScript
2
star
32

wildcard

Solutions to wildcard programming challenge
JavaScript
1
star
33

seq

Generate strings from a sequence.
JavaScript
1
star
34

emmet-vim-snippets

emmet-vim snippets for personal usage
CSS
1
star