division
Version:
Simple yet powerful wrapper over node.js cluster API. This module is inspired by impressive, but abandoned project Cluster created by TJ Holowaychuk.
68 lines (64 loc) • 1.7 kB
JavaScript
var fs, path;
fs = require('fs');
path = require('path');
module.exports = function(files, options) {
var extensions, ignored, interval, resolvePath, traverse, watch, __dirname__;
if (options == null) {
options = {};
}
__dirname__ = process.cwd();
if (!files) {
files = __dirname__;
}
if (!Array.isArray(files)) {
files = [files];
}
ignored = ['node_modules', 'test', 'bin', '.git'].concat(options.ignored);
interval = options.interval || 100;
extensions = options.extensions || ['.js'];
resolvePath = function(path) {
if ('/' === path[0]) {
return path;
} else {
return __dirname__ + '/' + path;
}
};
traverse = function(file) {
file = resolvePath(path.normalize(file));
return fs.stat(file, function(error, stat) {
if (!error) {
if (stat.isDirectory()) {
if (~ignored.indexOf(path.basename(file))) {
return;
}
return fs.readdir(file, function(err, files) {
return files.map(function(f) {
return file + '/' + f;
}).forEach(traverse);
});
} else {
if (file !== process.argv[1]) {
return watch(file);
}
}
}
});
};
watch = (function(_this) {
return function(file) {
if (!~extensions.indexOf(path.extname(file))) {
return;
}
return fs.watchFile(file, {
interval: interval,
persistent: false
}, function(curr, prev) {
if (curr.mtime > prev.mtime) {
_this.emit('filechange', file);
return _this.restart();
}
});
};
})(this);
return files.forEach(traverse);
};