Identify the logical error in the following Node.js code that uses `child_process.fork` for a calculation. The parent process logs the result, but it will always log `undefined`.
Node.js interview question for Advanced practice.
Answer
The console.log statement in the parent executes before the asynchronous 'message' event from the child is received.
Explanation
The error lies in the asynchronous nature of the communication. The parent process sends the message to the child and immediately continues to the console.log line. At this point, the child has not had time to perform the calculation and send the message back. Therefore, factorialResult is still undefined. The console.log statement must be placed inside the child.on('message', ...) callback to execute only after the result has been received.