1 | 'use strict';
|
2 |
|
3 | var chokidar = require('chokidar');
|
4 | var debounce = require('lodash.debounce');
|
5 | var asyncDone = require('async-done');
|
6 | var assignWith = require('lodash.assignwith');
|
7 |
|
8 | function assignNullish(objValue, srcValue) {
|
9 | return (srcValue == null ? objValue : srcValue);
|
10 | }
|
11 |
|
12 | var defaults = {
|
13 | ignoreInitial: true,
|
14 | delay: 200,
|
15 | queue: true,
|
16 | };
|
17 |
|
18 | function watch(glob, options, cb) {
|
19 | if (typeof options === 'function') {
|
20 | cb = options;
|
21 | options = {};
|
22 | }
|
23 |
|
24 | var opt = assignWith({}, defaults, options, assignNullish);
|
25 |
|
26 | var queued = false;
|
27 | var running = false;
|
28 |
|
29 | var watcher = chokidar.watch(glob, opt);
|
30 |
|
31 | function runComplete(err) {
|
32 | running = false;
|
33 |
|
34 | if (err) {
|
35 | watcher.emit('error', err);
|
36 | }
|
37 |
|
38 |
|
39 | if (queued) {
|
40 | queued = false;
|
41 | onChange();
|
42 | }
|
43 | }
|
44 |
|
45 | function onChange() {
|
46 | if (running) {
|
47 | if (opt.queue) {
|
48 | queued = true;
|
49 | }
|
50 | return;
|
51 | }
|
52 |
|
53 | running = true;
|
54 | asyncDone(cb, runComplete);
|
55 | }
|
56 |
|
57 | if (typeof cb === 'function') {
|
58 | var fn = debounce(onChange, opt.delay, opt);
|
59 | watcher
|
60 | .on('change', fn)
|
61 | .on('unlink', fn)
|
62 | .on('add', fn);
|
63 | }
|
64 |
|
65 | return watcher;
|
66 | }
|
67 |
|
68 | module.exports = watch;
|