-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwatch.js
More file actions
50 lines (42 loc) · 1.34 KB
/
watch.js
File metadata and controls
50 lines (42 loc) · 1.34 KB
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
#!/usr/bin/env node
'use strict';
const { spawn } = require('child_process');
const fs = require('fs');
const path = require('path');
let nodeProcess = null;
let debounceTimeout = null;
const ENTRY_FILE = 'index.js';
const DEBOUNCE_DELAY = 300; // 3ms
// start the server
function startServer() {
if (nodeProcess) nodeProcess.kill();
nodeProcess = spawn('node', [ENTRY_FILE], {
stdio: 'inherit'
});
console.log('[watch] server restarted\n');
}
// Recursively watch js files (excluding node_modules)
function watchDirectory(dir) {
fs.readdirSync(dir, { withFileTypes: true }).forEach((entry) => {
const fullPath = path.join(dir, entry.name);
if (entry.isDirectory()) {
if (entry.name === 'node_modules' || entry.name.startsWith('.')) return;
watchDirectory(fullPath); // recurse
} else if (entry.isFile() && fullPath.endsWith('.js')) {
watchFile(fullPath)
}
});
}
function watchFile(filePath) {
fs.watchFile(filePath, { interval: 100 }, () => {
clearTimeout(debounceTimeout);
debounceTimeout = setTimeout(() => {
console.log(`[watch] changes detected: ${filePath}`);
startServer();
}, DEBOUNCE_DELAY);
});
}
// watch
console.log('[watch] Watching project files..\n')
startServer();
watchDirectory(process.cwd())