-
Notifications
You must be signed in to change notification settings - Fork 3
/
watch.js
84 lines (69 loc) · 1.78 KB
/
watch.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
'use strict'
const fs = require('fs')
const path = require('path')
const events = require('events')
module.exports = function Watch (opts) {
opts = opts || {}
const pattern = opts.pattern
if (typeof opts.dir === 'undefined') {
throw new Error('dir parameter required')
}
let dirs = {
[opts.dir]: null
}
let e = new events.EventEmitter()
const cb = p => {
fs.stat(p, (err, stat) => {
if (err) { // must have been deleted
const isDir = !!dirs[p]
if (isDir || pattern.test(p)) {
e.emit('_removed', p, isDir)
dirs[p] && dirs[p].close()
delete dirs[p]
}
} else {
if (stat.isDirectory()) {
if (dirs[p]) return
e.emit('_modified', p, true)
dirs[p] = fs.watch(p, (_, file) => {
cb(path.join(p, file))
})
} else if (pattern.test(p)) {
e.emit('_modified', p)
}
}
})
}
const readDirs = (dir, done) => {
if (!dir) return
fs.readdir(dir, (err, files) => {
if (err) return done(err)
let i = 0
;(function next () {
let file = files[i++]
if (!file) return done(null)
const filepath = path.join(dir, file)
fs.stat(filepath, (err, stat) => {
if (err) return done(err)
if (stat && stat.isDirectory()) {
dirs[filepath] = null
return readDirs(filepath, next)
}
next()
})
}())
})
}
const watch = err => {
if (err) return e.emit('error', err)
Object.keys(dirs).map(loc => {
if (dirs[loc]) return
dirs[loc] = fs.watch(loc, (_, file) => {
cb(path.join(loc, file))
})
})
}
readDirs(opts.dir, watch)
e.addDir = p => readDirs(p, watch)
return e
}