import { spawn } from "child_process"; /** * Object to store references to spawned processes. * @type {Object.} */ const runningProcesses = {}; /** * Launches a new process if it's not already running. * @param {string} processName - The name of the process to launch. * @param {string[]} args - The arguments to pass to the process. * @param {boolean} waitForClose - Set this to wait to return until the process exits */ export const launchProcess = (processName, args, waitForClose=false) => { if (!runningProcesses[processName]) { const childProcess = spawn(processName, args); // Store reference to the spawned process runningProcesses[processName] = childProcess; let code = new Promise(res => { childProcess.on('exit', (code, signal) => { // Remove reference to the process when it exits delete runningProcesses[processName]; console.log(`${processName} process exited with code ${code} and signal ${signal}`); res(code); }) }); if (waitForClose === true) { return code } console.log(`${processName} process started.`); } else { console.log(`${processName} process is already running.`); } } /** * Checks the status of a process. * @param {string} processName - The name of the process to check. * @returns {string} A message indicating whether the process is running or not. */ export const checkProcessStatus = (processName) => { const childProcess = runningProcesses[processName]; if (childProcess) { // Check if the process is running if (!childProcess.killed) { return `${processName} process is running.`; } else { return `${processName} process is not running.`; } } else { return `${processName} process is not running.`; } } /** * Kills a running process. * @param {string} processName - The name of the process to kill. */ export const killProcess = (processName) => { const childProcess = runningProcesses[processName]; if (childProcess) { childProcess.kill(); console.log(`${processName} process killed.`); } else { console.log(`${processName} process is not running.`); } } export const getRunningProcesses = () => runningProcesses;