Skip to content

Commit 40f6906

Browse files
improve handling of child processes
1 parent cca1604 commit 40f6906

1 file changed

Lines changed: 42 additions & 7 deletions

File tree

scripts/dev/index.mjs

Lines changed: 42 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,17 @@
11
import { watch, existsSync } from 'node:fs';
22
import { join, extname, dirname } from 'node:path';
3-
import { execFile, spawn } from 'node:child_process';
3+
import { execFile, spawn as nativeSpawn } from 'node:child_process';
44
import { promisify } from 'node:util';
5+
import { fileURLToPath } from 'node:url';
56

67
const execFileAsync = promisify(execFile);
78

9+
const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..', '..');
10+
811
async function runDocKit(filePath = null) {
12+
const docKitBin = join(ROOT, 'node_modules', '.bin', 'doc-kit');
13+
914
const args = [
10-
'-p',
11-
'@node-core/doc-kit',
12-
'doc-kit',
1315
'generate',
1416
'-t',
1517
'web',
@@ -33,7 +35,7 @@ async function runDocKit(filePath = null) {
3335
args.push('-o', outPath);
3436
}
3537

36-
await execFileAsync('npx', args, { shell: true });
38+
await execFileAsync(docKitBin, args, { shell: true });
3739
console.log('\nBuild completed');
3840
}
3941

@@ -83,7 +85,7 @@ const handleFileChange = (baseDir, filename) => {
8385
}
8486

8587
isBuilding = false;
86-
}, 150);
88+
}, 500);
8789
};
8890

8991
// Dynamically watch all relevant directories if they exist
@@ -98,5 +100,38 @@ for (const dir of watchDirs) {
98100
}
99101

100102
// --- LOCAL SERVER ---
103+
104+
const children = new Set();
105+
106+
const spawn = (cmd, args) => {
107+
const child = nativeSpawn(cmd, args, {
108+
stdio: 'inherit',
109+
shell: true,
110+
});
111+
112+
children.add(child);
113+
child.once('close', () => children.delete(child));
114+
child.once('error', () => children.delete(child));
115+
116+
return child;
117+
};
118+
119+
const cleanup = () => {
120+
for (const child of children) {
121+
if (!child.killed) {
122+
child.kill('SIGINT');
123+
}
124+
}
125+
process.exit();
126+
};
127+
128+
process.on('SIGINT', cleanup);
129+
process.on('SIGTERM', cleanup);
130+
process.on('exit', () => {
131+
for (const child of children) {
132+
if (!child.killed) child.kill();
133+
}
134+
});
135+
101136
console.log('\nStarting local server...');
102-
spawn('npx', ['serve', './out'], { stdio: 'inherit', shell: true });
137+
spawn('npx', ['serve', './out']);

0 commit comments

Comments
 (0)