workforce
Version:
A cluster manager inspired by Learnboost's cluster.
70 lines (60 loc) • 1.84 kB
JavaScript
/**
* Deps.
*/
var fs = require('fs')
, path = require('path')
, debug = require('debug')('workforce:plugins:watch');
/**
* Restarts the server when `files` have changed.
*
* Attribution -- learnbooster/cluster:
* https://github.com/LearnBoost/cluster/blob/master/lib/plugins/reload.js
*
* Options:
*
* - `interval` Watch interval, defaults to 100
* - `extensions` File extensions to watch, defaults to ['.js']
* - `ignore` Directores to ignore. Merges with ['.git', 'node_modules']
*/
module.exports = exports = function(files, options){
options = options || {};
var interval = options.interval || 100
, ignore = options.ignore || ['.git', 'node_modules']
, extensions = options.extensions || ['.js'];
return function(workforce){
if (!files) files = [workforce.dir];
if (!Array.isArray(files)) files = [files];
debug('loaded');
files.forEach(traverse);
function traverse(file){
fs.stat(file, function(err, stat){
if (err) return console.error(err.messsage);
if (stat.isDirectory()) {
readDirectory(file);
} else if (stat.isFile()) {
watchFile(file);
}
});
}
function readDirectory(file){
if (~ignore.indexOf(path.basename(file))) return;
debug('watching %s', file);
var join = path.join.bind(path, file);
fs.readdir(file, function(err, files){
files
.map(join)
.forEach(traverse);
});
}
function watchFile(file){
if (!~extensions.indexOf(path.extname(file))) return;
var settings = { interval: interval, persistent: false };
fs.watchFile(file, settings, function(curr, prev){
if (curr.mtime > prev.mtime) {
debug('file change -- %s', file);
workforce.restart();
}
});
}
};
};