|
| 1 | +import { spawn } from 'child_process'; |
| 2 | + |
| 3 | +function startProcess(command, args = [], successMessage = '', cwd = process.cwd()) { |
| 4 | + return new Promise((resolve, reject) => { |
| 5 | + console.log(`Starting process: ${command} ${args.join(' ')} in ${cwd}`); |
| 6 | + const processInstance = spawn(command, args, { |
| 7 | + stdio: ['pipe', 'pipe', 'inherit'], |
| 8 | + shell: true, |
| 9 | + cwd, |
| 10 | + }); |
| 11 | + |
| 12 | + processInstance.stdout.on('data', (data) => { |
| 13 | + const output = data.toString(); |
| 14 | + console.log(output); |
| 15 | + if (successMessage && output.includes(successMessage)) { |
| 16 | + console.log('Process launched successfully.'); |
| 17 | + resolve(processInstance); |
| 18 | + } |
| 19 | + }); |
| 20 | + |
| 21 | + processInstance.on('error', (error) => { |
| 22 | + console.error('Error starting process:', error); |
| 23 | + reject(error); |
| 24 | + }); |
| 25 | + |
| 26 | + processInstance.on('close', (code) => { |
| 27 | + console.log(`Process exited with code ${code}`); |
| 28 | + reject(new Error(`Process exited unexpectedly with code ${code}`)); |
| 29 | + }); |
| 30 | + }); |
| 31 | +} |
| 32 | + |
| 33 | +function stopProcess(processInstance) { |
| 34 | + return new Promise((resolve, reject) => { |
| 35 | + if (!processInstance) { |
| 36 | + console.log('No process is running.'); |
| 37 | + return reject(new Error('No process is running.')); |
| 38 | + } |
| 39 | + |
| 40 | + console.log('Stopping process...'); |
| 41 | + // processInstance.kill('SIGINT'); |
| 42 | + processInstance.kill('SIGKILL'); |
| 43 | + resolve(); |
| 44 | + }); |
| 45 | +} |
| 46 | + |
| 47 | +process.on('SIGINT', async () => { |
| 48 | + console.log('\nCaught interrupt signal.'); |
| 49 | + process.exit(); |
| 50 | +}); |
| 51 | + |
| 52 | +process.on('SIGTERM', async () => { |
| 53 | + console.log('\nReceived termination signal.'); |
| 54 | + process.exit(); |
| 55 | +}); |
| 56 | + |
| 57 | +export { startProcess, stopProcess }; |
0 commit comments