Debian Codegraph @

fs2/watch-path.js

raw
1 "use strict";
2
3 var ee = require("event-emitter")
4 , pathUtils = require("path")
5 , watch = require("./watch").watch;
6
7 var basename = pathUtils.basename
8 , dirname = pathUtils.dirname
9 , join = pathUtils.join
10 , resolve = pathUtils.resolve
11 , Watcher;
12
13 Watcher = function (path) {
14 this.path = path;
15 this.missing = [];
16 this.onchange = this.onchange.bind(this);
17 this.onremove = this.onremove.bind(this);
18 this.up = this.up.bind(this);
19 this.watch();
20 this.emitter = ee();
21 this.emitter.close = this.close.bind(this);
22 return this.emitter;
23 };
24
25 Watcher.prototype = {
26 close: function () { this.watcher.close(); },
27 up: function () {
28 var parent = dirname(this.path);
29 if (parent === this.path) {
30 return;
31 }
32 this.missing.unshift(basename(this.path));
33 this.path = parent;
34 this.watch();
35 },
36 watch: function () {
37 var watcher;
38 try {
39 watcher = watch(this.path);
40 } catch (e) {
41 this.up();
42 return;
43 }
44 this.onwatch(watcher);
45 },
46 tryDown: function () {
47 var watcher, npath;
48 npath = join(this.path, this.missing[0]);
49 try { watcher = watch(npath); }
50 catch (e) { return false; }
51 this.path = npath;
52 this.missing.shift();
53 if (!this.missing.length) {
54 this.onwatch(watcher);
55 this.oncreate();
56 } else if (this.tryDown()) {
57 watcher.close();
58 } else {
59 this.onwatch(watcher);
60 }
61 return true;
62 },
63 onwatch: function (watcher) {
64 if (this.missing.length) {
65 watcher.on(
66 "change",
67 function () {
68 if (this.tryDown()) {
69 watcher.close();
70 }
71 }.bind(this)
72 );
73 watcher.once("end", this.up);
74 } else {
75 watcher.on("change", this.onchange);
76 watcher.once("end", this.onremove);
77 }
78 this.watcher = watcher;
79 },
80 oncreate: function () { this.emitter.emit("change", { type: "create" }); },
81 onchange: function () { this.emitter.emit("change", { type: "modify" }); },
82 onremove: function () {
83 this.emitter.emit("change", { type: "remove" });
84 this.up();
85 }
86 };
87
88 module.exports = exports = function (path) { return new Watcher(resolve(String(path))); };
89 exports.WatchPath = Watcher;