Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 31 additions & 9 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ var copy = require('shallow-copy');
var browserify = require('browserify');
var fs = require('fs');
var chokidar = require('chokidar');
var listenerCount = require('events').EventEmitter.listenerCount;

module.exports = watchify;
watchify.browserify = browserify;
Expand All @@ -18,6 +19,8 @@ function watchify (opts) {
var queuedDeps = {};
var changingDeps = {};
var first = true;
var watchers = {};
var listeners = {};

if (opts.cache) {
cache = opts.cache;
Expand All @@ -29,6 +32,11 @@ function watchify (opts) {
pkgcache = opts.pkgcache;
delete opts.pkgcache;
}

if (opts.watchers) {
watchers = opts.watchers;
delete opts.watchers;
}

b.on('package', function (file, pkg) {
pkgcache[file] = pkg;
Expand Down Expand Up @@ -60,18 +68,26 @@ function watchify (opts) {
});
});

var watchers = {};
function addDep (dep) {
if (watching[dep.id]) return;
watching[dep.id] = true;
cache[dep.id] = dep;

var watcher = chokidar.watch(dep.id, {persistent: true});
watchers[dep.id] = watcher;
watcher.on('error', b.emit.bind(b, 'error'));
watcher.on('change', function () {
invalidate(dep.id);
});
var watcher = watchers[dep.id];
if (!watcher) {
watcher = watchers[dep.id] = chokidar.watch(dep.id, {persistent: true});
b.emit('watch', watcher, dep);
}

listeners[dep.id] = {
err: b.emit.bind(b, 'error'),
change: function () {
invalidate(dep.id);
}
};

watcher.on('error', listeners[dep.id].err);
watcher.on('change', listeners[dep.id].change);
}

function invalidate (id) {
Expand Down Expand Up @@ -129,9 +145,15 @@ function watchify (opts) {
outStream.on('close', close);
function close () {
first = false;
var depId;
var depId, watcher;
for (depId in queuedCloses) {
queuedCloses[depId].close();
watcher = watchers[depId];
watcher.removeListener('change', listeners[depId].change);
watcher.removeListener('error', listeners[depId].err);
if (!listenerCount(watcher, 'change') && !listenerCount(watcher, 'error')) {
watcher.close();
watchers[depId] = null;
}
watching[depId] = false;
}
queuedCloses = {};
Expand Down