Which of the following best explains why process management is crucial in Node.js applications?
Think about how Node.js handles many users at once without slowing down.
Node.js uses an event loop that runs in a single thread. Process management, like creating child processes, helps handle heavy tasks without blocking this loop, keeping the app responsive.
Consider a Node.js app that spawns a child process to handle a task. What is the expected behavior when the child process exits unexpectedly?
Think about how you can keep your app running smoothly even if a part of it stops.
Node.js allows the main process to listen for child process events like 'exit'. This way, it can handle unexpected exits by restarting the child process or logging the error.
Which code snippet correctly spawns a child process to run a script named worker.js using Node.js child_process module?
const { spawn } = require('child_process');
// Choose the correct option belowRemember that spawn takes the command as first argument and an array of arguments as second.
The spawn function requires the command as a string and the arguments as an array. Option D correctly uses 'node' as the command and ['worker.js'] as the argument array.
Review the code below. Why does the child process not restart after it exits?
const { spawn } = require('child_process');
function startChild() {
const child = spawn('node', ['worker.js']);
child.on('exit', () => {
console.log('Child exited');
});
}
startChild();Look at what happens inside the 'exit' event handler.
The code logs when the child exits but does not restart it. To restart, the 'exit' event handler must call startChild() again.
Consider the following Node.js code that manages a child process. What will be printed to the console?
const { spawn } = require('child_process');
let restartCount = 0;
function startChild() {
const child = spawn('node', ['-e', "console.log('Child running'); process.exit(1);"]);
child.on('exit', (code) => {
console.log(`Child exited with code ${code}`);
if (restartCount < 2) {
restartCount++;
startChild();
} else {
console.log('Max restarts reached');
}
});
}
startChild();Count how many times the child process starts and exits before stopping.
The child process prints 'Child running' then exits with code 1. The main process restarts it twice (total 3 runs). After the third exit, it prints 'Max restarts reached'.