function _unwatchPath(path) {
var watcher = _watcherMap[path];
if (watcher) {
try {
if (fsevents) {
watcher.stop();
} else {
watcher.close();
}
} catch (err) {
console.warn("Failed to unwatch file " + path + ": " + (err && err.message));
} finally {
delete _watcherMap[path];
}
}
}
Initialize the "fileWatcher" domain. The fileWatcher domain handles watching and un-watching directories.
function init(domainManager) {
if (!domainManager.hasDomain("fileWatcher")) {
domainManager.registerDomain("fileWatcher", {major: 0, minor: 1});
}
domainManager.registerCommand(
"fileWatcher",
"watchPath",
watchPath,
false,
"Start watching a file or directory",
[{
name: "path",
type: "string",
description: "absolute filesystem path of the file or directory to watch"
}]
);
domainManager.registerCommand(
"fileWatcher",
"unwatchPath",
unwatchPath,
false,
"Stop watching a single file or a directory and it's descendants",
[{
name: "path",
type: "string",
description: "absolute filesystem path of the file or directory to unwatch"
}]
);
domainManager.registerCommand(
"fileWatcher",
"unwatchAll",
unwatchAll,
false,
"Stop watching all files and directories"
);
domainManager.registerEvent(
"fileWatcher",
"change",
[
{name: "path", type: "string"},
{name: "event", type: "string"},
{name: "filename", type: "string"}
]
);
_domainManager = domainManager;
}
exports.init = init;
Un-watch all files and directories.
function unwatchAll() {
var path;
for (path in _watcherMap) {
if (_watcherMap.hasOwnProperty(path)) {
unwatchPath(path);
}
}
}
Un-watch a file or directory. For directories, unwatch all descendants.
function unwatchPath(path) {
Object.keys(_watcherMap).forEach(function (keyPath) {
if (keyPath.indexOf(path) === 0) {
_unwatchPath(keyPath);
}
});
}
Watch a file or directory.
function watchPath(path) {
if (_watcherMap.hasOwnProperty(path)) {
return;
}
try {
var watcher;
if (fsevents) {
watcher = fsevents(path);
watcher.on("change", function (filename, info) {
var parent = filename && (fspath.dirname(filename) + "/"),
name = filename && fspath.basename(filename),
type;
switch (info.event) {
case "modified": // triggered by file content changes
case "unknown": // triggered by metatdata-only changes
type = "change";
break;
default:
type = "rename";
}
_domainManager.emitEvent("fileWatcher", "change", [parent, type, name]);
});
} else {
watcher = fs.watch(path, {persistent: false}, function (event, filename) {
// File/directory changes are emitted as "change" events on the fileWatcher domain.
_domainManager.emitEvent("fileWatcher", "change", [path, event, filename]);
});
}
_watcherMap[path] = watcher;
watcher.on("error", function (err) {
console.error("Error watching file " + path + ": " + (err && err.message));
unwatchPath(path);
});
} catch (err) {
console.warn("Failed to watch file " + path + ": " + (err && err.message));
}
}