--- description: Guidelines for proper process cleanup in Node/Bun scripts globs: **/*.{js,ts} --- When managing long-running processes in Node/Bun scripts: 1. Always track processes globally: ```js let currentProcess = null; ``` 2. Set up cleanup handlers at the top level: ```js // Basic cleanup process.on('exit', () => { if (currentProcess?.exitCode === null) { currentProcess.kill('SIGTERM'); } }); // Handle interrupts ['SIGINT', 'SIGTERM'].forEach(signal => { process.on(signal, () => { if (currentProcess?.exitCode === null) { currentProcess.kill('SIGTERM'); } process.exit(); }); }); ``` 3. Always check process state before killing: ```js if (process?.exitCode === null) { process.kill('SIGTERM'); } ``` 4. Use timeouts for process startup: ```js const startupTimeout = setTimeout(() => { if (process.exitCode === null) { process.kill('SIGTERM'); } reject(new Error('Process startup timeout')); }, timeoutMs); ``` 5. Clean up in both try/catch and finally blocks: ```js try { // ... process work ... } catch (error) { cleanup(); throw error; } finally { cleanup(); } ``` metadata: priority: high version: 1.0 examples: - input: | # Starting a server process const server = spawn('server'); output: | let currentServer = null; process.on('exit', () => { if (currentServer?.exitCode === null) { currentServer.kill('SIGTERM'); } }); const server = spawn('server'); currentServer = server;