Last active
November 27, 2021 14:22
-
-
Save stephanbogner/63ac76b97ce54fc78d75911c652da12d to your computer and use it in GitHub Desktop.
Run child processes in Nodejs in queue (in my example the Astro build process)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { spawn } = require('child_process'); | |
let queue = ['A', 'B']; | |
let currentlyProcessing = false; | |
const addToQueueContinueWithNext = (newItem) => { | |
queue.push(newItem); | |
checkQueueAndStartIfIdle(); | |
} | |
const removeFirstItemFromQueueContinueWithNext = () => { | |
queue.shift(); | |
checkQueueAndStartIfIdle(); | |
} | |
const checkQueueAndStartIfIdle = () => { | |
if(currentlyProcessing === false && queue.length > 0){ | |
const nextProcess = queue[0]; | |
startProcessing(nextProcess); | |
}else{ | |
console.log('- Queue is empty or already processing. Queue:', currentlyProcessing, ' Currently processing:',queue) | |
} | |
} | |
const startProcessing = async(processId) => { | |
console.log('---------------------'); | |
currentlyProcessing = true; | |
await childProcess(processId); | |
currentlyProcessing = false; | |
removeFirstItemFromQueueContinueWithNext(); | |
} | |
const childProcess = async(processId) => { | |
console.log('- Run Astro build process for', processId); | |
const childProcess = spawn('npm', ['run', 'astro-build']); | |
childProcess.stdout.on('data', (data) => { | |
console.log(` - Log: ${data}`); | |
}); | |
childProcess.stderr.on('data', (data) => { | |
console.error(` - Error: ${data}`); | |
}); | |
const exitCode = await new Promise( (resolve, reject) => { | |
childProcess.on('close', resolve); | |
}); | |
console.log(` - Done: Child process exited with code ${exitCode}`); | |
return true; | |
} | |
addToQueueContinueWithNext('C'); | |
// checkQueueAndStartIfIdle() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment