child process in Node JS

ref – https://www.digitalocean.com/community/tutorials/how-to-launch-child-processes-in-node-js

Creating a Child Process with fork()

index.js

Fork is a variation of spawn. To create a process that’s also a Node Process.

Main benefit of fork over (exec, spawn) is that fork enables communication between the parent and child process.

CPU intensive tasks (iterating over large loops, parsing large JSON) stop other JS code from running. If a web server is blocked, it cannot process any new incoming requests until the blocking code has completed its execution.

1) Now run the server
2) run /hello (1st time)
3) run /total
4) run /hello (2nd time)

So we’ll only see the result from the first /hello. The slow function will block other code, and that’s why we won’t see the 2nd /hello.

The blocking code is slowFunction.

So how do we solve this?

Move blocking code to own module:

getCount.js

Since it will be run with fork, we can add code to communicate with the parent process when slowFunction has completed processing. Let’s send a message to the parent process with JSON message.

– Why look for message ‘START’? Our server code will send the START event when someone access the ‘/total’ endpoint.
– Upon receiving that event, we run slowFunction().
– we use process.send() to send a message to the parent process.

index.js

getCount.js

Run the app: node index.js

Open a 2nd terminal and type: curl http://localhost:8000/total
This will start up a long running task at say 7:41:18.

Open a 3rd terminal and type: curl http://localhost:8000/hello

Hi it a bunch of times. As you can see, it is running concurrently and not blocking the main JS code. This is because its a child process that’s running it concurrently. From the time stamp, you will also see that it’s happening after 7:41:18.

Then when the long task is done, it stops at 7:42:20. This proves that the /hello logs before 7:42:20 were all done concurrently with the task at /total.