What is a Child Process in Node.js?

CWC
2 Min Read

Sometimes you need to have your Node process start another program. This can easily be done by using the child_process module.

I/O works well with Node because of its event-driven asynchronous model, but cases in which heavy CPU resources are required for tasks, the event loop could be blocked, which limits responsiveness overall. Such CPU-heavy tasks are best performed by a separate process, keeping the event loop free.

Node allows developers to create a new process and assign the new task to this process via the child_process module. You may also need to use the module when an external command needs to be executed from node and you are looking to get the result after the command has finished.

Three ways to create a child process in Node are exec, execFile, and the spawn method.

exec

The simplest way is the .exec method. Also known as the fire, forget, and buffer formula, child_process.exec basically runs your process, buffers the output, and allows you access from a callback when the process is finished. As the .exec buffers the output of the new process for, it also returns a ChildProcess object.

execFile

Almost like the .exec method, .execFile has two minor but significant differences. In short, this method doesn’t spawn a new shell and the command is not the first argument but rather the name of the file meant to be executed.

Spawn

The first two methods are used simply to execute a command and reach the output goal. Spawn, on the other hand is used for more complex interactions between the child and parent processes. A very important property of the configuration object in this case is stdio, which will either accept an array or one of three strings – ignore’,’pipe’,’inherit’. The spawn method includes numerous events and methods used interact with the child process in various ways.

[vc_row][vc_column][td_block_21 separator=”” tag_slug=”node-js” limit=”40″ tdc_css=””][/vc_column][/vc_row]

TAGGED:
Share This Article
Leave a comment

Leave a Reply

Your email address will not be published. Required fields are marked *

English
Exit mobile version