twreporter-react
Version:
React-Redux site for The Reporter Foundation in Taiwan
100 lines (93 loc) • 3.12 kB
JavaScript
// Generated by CoffeeScript 1.10.0
(function() {
var cluster, colors, options, path;
cluster = require("cluster");
path = require("path");
colors = require("colors");
options = {
hook: false,
includeModules: false,
main: require.main.filename,
ignore: /(\/\.|~$)/,
respawnOnExit: true
};
module.exports = function(ops) {
var chokidar, fixChokidar, initial, key, lastErr, respawnPending, value, watcher;
if (typeof ops === "string" || ops instanceof String) {
options.main = path.resolve(ops);
} else {
for (key in ops) {
value = ops[key];
options[key] = value;
}
}
if (cluster.isMaster) {
cluster.setupMaster({
exec: path.join(path.dirname(module.filename), "launcher.js")
});
chokidar = require("chokidar");
fixChokidar = function(file) {
return file.slice(0, -1) + "[" + file.slice(-1) + "]";
};
initial = options.hook ? fixChokidar(options.main) : path.dirname(options.main);
watcher = chokidar.watch(initial, {
ignored: options.ignore,
ignoreInitial: true,
usePolling: options.usePolling,
interval: options.interval || 100,
binaryInterval: options.binaryInterval || 300
});
cluster.fork();
respawnPending = false;
lastErr = "";
cluster.on("exit", function(dead, code, signal) {
var hasWorkers, id, ref, worker;
hasWorkers = false;
ref = cluster.workers;
for (id in ref) {
worker = ref[id];
hasWorkers = true;
}
if (!hasWorkers && (respawnPending || options.respawnOnExit)) {
cluster.fork();
return respawnPending = false;
}
});
cluster.on("online", function(worker) {
worker.send(options);
return worker.on("message", function(message) {
if (message.err && (!options.respawnOnExit || message.err !== lastErr)) {
console.log("[piping]".bold.red, "can't execute file:", options.main);
console.log("[piping]".bold.red, "error given was:", message.err);
if (options.respawnOnExit) {
lastErr = message.err;
return console.log("[piping]".bold.red, "further repeats of this error will be suppressed...");
}
} else if (message.file) {
if (options.usePolling) {
return watcher.add(message.file);
} else {
return watcher.add(fixChokidar(message.file));
}
}
});
});
watcher.on("change", function(file) {
var id, ref, worker;
console.log("[piping]".bold.red, "File", path.relative(process.cwd(), file), "has changed, reloading.");
ref = cluster.workers;
for (id in ref) {
worker = ref[id];
respawnPending = true;
process.kill(worker.process.pid, 'SIGTERM');
}
if (!respawnPending) {
return cluster.fork();
}
});
return false;
} else {
return true;
}
};
}).call(this);