| 1 |
"use strict"; |
| 2 |
|
| 3 |
var promisify = require("deferred").promisify |
| 4 |
, ee = require("event-emitter") |
| 5 |
, fs = require("fs") |
| 6 |
, typeByStats = require("../type-by-stats"); |
| 7 |
|
| 8 |
var nextTick = process.nextTick |
| 9 |
, lstat = promisify(fs.lstat) |
| 10 |
, watch = fs.watch |
| 11 |
, opts = { persistent: false }; |
| 12 |
|
| 13 |
module.exports = function (path, emitter) { |
| 14 |
var stats, fileType, listener, watcher, lock, end, clearLock, close; |
| 15 |
|
| 16 |
end = function (err) { |
| 17 |
if (emitter) { |
| 18 |
emitter.emit("end", err); |
| 19 |
close(); |
| 20 |
} |
| 21 |
}; |
| 22 |
|
| 23 |
close = function () { |
| 24 |
if (emitter) { |
| 25 |
watcher.close(); |
| 26 |
emitter = null; |
| 27 |
} |
| 28 |
}; |
| 29 |
|
| 30 |
clearLock = function () { lock = null; }; |
| 31 |
|
| 32 |
listener = function (type) { |
| 33 |
if (lock) return; |
| 34 |
if (lock === false) { |
| 35 |
lock = type === "rename"; |
| 36 |
return; |
| 37 |
} |
| 38 |
lock = type === "rename"; |
| 39 |
// We do timeout, as there are cases that reinitializing watcher right away |
| 40 |
// doesn't work as file is not accessible. It gives us false positive that |
| 41 |
// file is removed (and that is not reported by dir watcher on parent dir) |
| 42 |
setTimeout(function () { |
| 43 |
var nwatcher; |
| 44 |
nextTick(clearLock); |
| 45 |
watcher.close(); |
| 46 |
try { |
| 47 |
nwatcher = watch(path, opts, listener); |
| 48 |
} catch (e) { |
| 49 |
end(e); |
| 50 |
return; |
| 51 |
} |
| 52 |
watcher = nwatcher; |
| 53 |
watcher.on("error", end); |
| 54 |
if (stats && (lock || stats.isFile())) { |
| 55 |
lstat(path).done(function (nstats) { |
| 56 |
var newFileType, err; |
| 57 |
if (!emitter) return; |
| 58 |
newFileType = typeByStats(nstats); |
| 59 |
if (fileType !== newFileType) { |
| 60 |
err = new Error("File type have changed"); |
| 61 |
err.code = "DIFFTYPE"; |
| 62 |
end(err); |
| 63 |
return; |
| 64 |
} |
| 65 |
if ( |
| 66 |
stats.isDirectory() || |
| 67 |
(stats.ctime.valueOf() !== nstats.ctime.valueOf() || |
| 68 |
(stats.mtime.valueOf() !== nstats.mtime.valueOf() || |
| 69 |
stats.size !== nstats.size)) |
| 70 |
) { |
| 71 |
emitter.emit("change"); |
| 72 |
} |
| 73 |
stats = nstats; |
| 74 |
}, end); |
| 75 |
} |
| 76 |
}, 10); |
| 77 |
}; |
| 78 |
|
| 79 |
watcher = watch(path, opts, listener); |
| 80 |
watcher.on("error", end); |
| 81 |
if (!emitter) emitter = ee(); |
| 82 |
emitter.end = end; |
| 83 |
emitter.close = close; |
| 84 |
lstat(path)(function (nstats) { |
| 85 |
stats = nstats; |
| 86 |
fileType = typeByStats(stats); |
| 87 |
}, end); |
| 88 |
return emitter; |
| 89 |
}; |