• No results found

5-5 Spawning a Child with spawn Problem

In document Node js Recipes Cory Gackenheimer pdf (Page 125-127)

You need to create a child process to execute an auxiliary action in your Node.js application.

Solution

There are many reasons why you would want to spawn a child process from your Node.js application. Several of these could simply be to execute a command-line task without the need to require or build an entire module for the application. In this solution you will highlight two command-line applications and a third solution that will execute another Node.js process from the spawn method.

Listing 5-16. Spawning Children /**

* .spawn */

var spawn = require('child_process').spawn, pwd = spawn('pwd'), ls = spawn('ls', ['-G']), nd = spawn('node', ['5-4-1.js']); pwd.stdout.setEncoding('utf8'); pwd.stdout.on('data', function(data) { console.log(data); }); pwd.stderr.on('data', function(data) { console.log(data); }); pwd.on('close', function(){ console.log('closed'); }); ls.stdout.setEncoding('utf8'); ls.stdout.on('data', function(data) { console.log(data); }); nd.stdout.setEncoding('utf8'); nd.stdout.on('data', function(data) { console.log(data); });

Chapter 5 ■ Using events and Child proCesses

The first spawn is to just run the ‘pwd’ command in the current directory; the second is to list all the files in that directory. These are just command-line utilities built into the operating system. However, the third example in this solution executes the command to run a Node.js file; then, like the previous examples, you log the output to the console.

How It Works

Spawning is one method for invoking a child process in Node.js and is a method of the child_process module. The child_process module creates a way to stream data through stdout, stdin, and stderr. Because of the nature of this module this can be done in a nonblocking way, fitting nicely into the Node.js model.

The child_process spawn method will instantiate a ChildProcess object, which is a Node.js EventEmitter. The events that are associated with the ChildProcess object are shown in Table 5-1.

Table 5-1. ChildProcess Events

Event

Detail

‘message’ Transfers a message object, which is JSON, or a value. This can also transfer a socket or server object as an optional second parameter.

‘error’ Transmits the error to the callback. This can happen when the child process fails to spawn, is unable to be killed, or the message transfer fails.

‘close’ Happens when all of the stdio streams of the child process are completed. This will transmit the exit code and the signal that was sent with it.

‘disconnect’ Emits when you terminate a connection by utilizing the .disconnect() method on the child (or parent).

‘exit’ Emits after the child process ends. If the process terminated normally, code is the final exit code of the process, otherwise null. If the process terminated due to receipt of a signal, signal is the string name of the signal, otherwise null.

Table 5-2. Stream Events of the Child Process and Other Methods

Method

Description

.stdin A writable stream that is representative of the child process stdin. .stdout A readable stream representing the stdout of the child process. .stderr A readable stream of the stderr of the child process.

.pid The child process process identifier (PID).

.kill Kills a process, optionally sends the termination signal. .disconnect Disconnects from the parent.

.send Sends a message to a .fork’d process. (There is more detail on this in Section 5-8.)

Aside from these ChildProcess events, the spawned child is also a stream, as you saw above. The stream contains the data from the standard I/O of the child processes. The methods that are associated with these streams are outlined in Table 5-2 along with other methods on the child.

Chapter 5 ■ Using events and Child proCesses

Now that you have a little more understanding of what the ChildProcess is and how that fits into the child_process module, you can see that your solution of spawning a child process invokes the process directly. You create three spawned processes. Each of these begins with a command argument. This argument, ‘pwd,’ ‘ls,’ ‘node’ is the command that will be executed as if you were running it on the command line in your terminal application. The next argument in the child_process.spawn method is an optional array of arguments to pass to the

command argument.

You see then that the spawned processes from this example are the same as running the following in the command line of your terminal:

$ pwd & $ ls –G &

$ node 5-4-1.js &

You can read the output of these commands from your spawned process as well. This happens by listening to the child_process.stdout stream. If you bind to the data event you see the standard output of these commands just as if you were running the command in the terminal. In the case of the third spawn, you see the output from the entire module from the previous section of this chapter.

There is also an optional third argument that can be present in the child_process.spawn method. This argument represents the set of options to help set up the spawned process. These options can have the values shown in Table 5-3.

5-6. Running Shell Commands with .exec

In document Node js Recipes Cory Gackenheimer pdf (Page 125-127)