forked from tikivn/tini-types
-
Notifications
You must be signed in to change notification settings - Fork 0
/
watch.js
56 lines (49 loc) · 1.32 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
function debounceLeading(func, timeout = 500) {
let timer;
return (...args) => {
if (!timer) {
func.apply(this, args);
}
clearTimeout(timer);
timer = setTimeout(() => {
timer = undefined;
}, timeout);
};
}
const chokidar = require("chokidar");
const { spawn, ChildProcessWithoutNullStreams } = require("child_process");
const watcher = chokidar.watch(["test/**/*.ts", "types/**/*.ts"], {});
/**
* @type {ChildProcessWithoutNullStreams}
*/
let child;
const excuteChild = debounceLeading(() => {
if (child) {
const killed = child.kill();
console.log(`child process is restarting, killed:${killed}`);
}
child = spawn("npm", ["run", "test"]);
child.stdout.on("data", (d) => console.log(d.toString()));
child.stderr.on("data", (d) => console.error(d.toString()));
child.on("error", (d) => console.error(d.toString()));
child.on("close", (code) => {
if (String(code) === "0") {
console.log(`done`);
return;
}
console.error(`child process exited with code ${code}`);
});
});
watcher.on("all", (ev, path) => {
if (ev === "add") {
console.log(`added file: ${path}`);
return;
}
if (ev === "change") {
console.log(`restart due to ${ev} file: ${path}`);
excuteChild();
return;
}
console.log(`watcher skipping ${ev}`);
});
excuteChild();