Improve subprocess handler
- Will now output the subprocess console when in dev mode
This commit is contained in:
@@ -1,4 +1,6 @@
|
||||
import { spawn } from "child_process";
|
||||
import dotenv from 'dotenv';
|
||||
dotenv.config()
|
||||
|
||||
/**
|
||||
* Object to store references to spawned processes.
|
||||
@@ -12,11 +14,11 @@ const runningProcesses = {};
|
||||
* @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, pcwd=undefined) => {
|
||||
export const launchProcess = (processName, args, waitForClose = false, pcwd = undefined) => {
|
||||
if (!runningProcesses[processName]) {
|
||||
let childProcess;
|
||||
if (pcwd) {
|
||||
childProcess = spawn(processName, args, {cwd: pcwd});
|
||||
childProcess = spawn(processName, args, { cwd: pcwd });
|
||||
}
|
||||
else {
|
||||
childProcess = spawn(processName, args);
|
||||
@@ -25,11 +27,29 @@ export const launchProcess = (processName, args, waitForClose=false, pcwd=undefi
|
||||
// Store reference to the spawned process
|
||||
runningProcesses[processName] = childProcess;
|
||||
|
||||
// Output the process output in development
|
||||
var scriptOutput = "";
|
||||
|
||||
// Get the stdout from the child process
|
||||
childProcess.stdout.setEncoding('utf8');
|
||||
childProcess.stdout.on('data', (data) => {
|
||||
if (process.env.NODE_ENV === "development") console.log(`Data from ${processName}:`, data);
|
||||
scriptOutput += data.toString();
|
||||
});
|
||||
|
||||
// Get the stderr from the child process
|
||||
childProcess.stderr.setEncoding('utf8');
|
||||
childProcess.stderr.on('data', (data) => {
|
||||
if (process.env.NODE_ENV === "development") console.log(`Data from ${processName}:`, data);
|
||||
scriptOutput += data.toString();
|
||||
})
|
||||
|
||||
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}`);
|
||||
console.log("Child process console output: ", scriptOutput);
|
||||
res(code);
|
||||
})
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user