Skip to content

Instantly share code, notes, and snippets.

@stephanbogner
Last active November 27, 2021 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stephanbogner/63ac76b97ce54fc78d75911c652da12d to your computer and use it in GitHub Desktop.
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)
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