Chapter 8

Creating and Controlling External Processes

WHAT’S IN THIS CHAPTER?

  • Launching commands and child processes
  • Sending and receiving data from a child process
  • Sending signals to and then terminating a child process

Node is designed to handle I/O efficiently, but, as you’ve seen, some types of programs are not a good fit for this model. For instance, if you were to perform a CPU-intensive task using Node, you would be blocking the event loop, thus limiting your application responsiveness. Instead, CPU-intensive tasks should be assigned to a different process, freeing the event loop. Node allows you to spawn processes that become children of the process that launched them — the parent. In Node, a child process has a two-way channel to communicate with the parent process, and the parent process can monitor and control the child to some degree.

Another instance of when you may want to use a child process is when you want to simply execute an external command from Node and get back the results once the command finishes. For instance, you may want to spawn a UNIX command, a script, or another type of utility that is not directly executable inside Node.

This chapter shows you how to spawn external commands and create, communicate with, and terminate child processes. The point is to enable you to accomplish multiple tasks outside of the Node process.

EXECUTING EXTERNAL COMMANDS

When you need to launch an external shell command or an executable file, you may do so by using the ...

Get Professional Node.js: Building Javascript Based Scalable Software now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.