Last active
August 29, 2015 14:22
-
-
Save toanalien/cf65484f057df609b138 to your computer and use it in GitHub Desktop.
Spawning child processes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* As you have seen, you can use the child_process.exec() function to launch external processes. | |
* You get your callback invoked when the process ends. This approach is very simple, but it has some drawbacks: | |
* > except for the command-line arguments and the environment variables, using exec() does not allow you to | |
* communicate with the child process. | |
* > the child process output is buffered. As a result, you cannot stream it, and it can consume memory. | |
* | |
* Fortunately, Node’s child_process module allows for finer-grained control when launching, stopping, | |
* and generally interacting with child processes. | |
* You may launch a new process, called the child process, from your application, which is called the parent process. | |
* Once you’ve launched a new child process, Node establishes a two-way communication channel, | |
* which both processes can use to send and receive data strings to and from each other. | |
* The parent process can also exercise some control over the child, sending it signals and forcing it to terminate. | |
* | |
* Creating the child process | |
*/ | |
var spawn = require('child_process').spawn; | |
var child = spawn('tail', ['-f', '/var/log/system.log']); | |
/** | |
* Here you spawn a child process to run a tail command, passing in arguments -f and /var/log/ system.log. | |
* This tail command will monitor the fi le in /var/log/system.log — if it exists — and output every new data | |
* appended to it into the stdout stream. The spawn function call returns a ChildProcess object, which is a handler | |
* object that encapsulates access to the real process. Here you assign this new descriptor to the variable named child. | |
*/ | |
// Listening for data from child process | |
/** | |
* Any child process handler has a property named stdout that represents the child process standard output as a stream. | |
* You can then bind to the data event on that stream, which is the same as saying | |
* “for every data chunk you get from the child output, invoke this callback.” Here is an example of that happening: | |
*/ | |
// print child output to the console | |
child.stdout.on('data', function(data) { | |
console.log('tail output: ' + data); | |
} | |
); | |
/** | |
* Sending Data to the child process | |
*/ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment