Introduction to NodeJS subprocess NodeJS subprocess provides important interfaces for interacting with the system. Its main APIs are: interfaces for standard input, standard output, and standard error output.
Introduction to NodeJS subprocess
NodeJS subprocess provides an important interface for interacting with the system. Its main APIs are:
Standard input, standard output and standard error output interface
child.stdin Get standard input
child.stdout Get standard output
child.stderr Get standard error output
Get the PID of the child process: child.pid
Provided Important methods for generating child processes: child_process.spawn(cmd, args=[], [options])
Provides important methods for directly executing system commands: child_process.exec(cmd, [options], callback)
Provided Method to kill the process: child.kill(signal='SIGTERM')
Example 1: Use the child process to obtain system memory usage
Save the following code as free.js:
var spawn = require( 'child_process').spawn,
free = spawn('free', ['-m']);
// Capture standard output and print it to the console
free.stdout .on('data', function (data) {
console.log('Standard output:
' data);
});
// Capture standard error output and print it to the console
free.stderr.on('data', function (data) {
console.log('Standard error output:
' data);
});
//Register child process shutdown event
free.on('exit', function (code, signal) {
console.log('child The process has exited, code: ' code);
});
Result after executing the code:
$ node free.js
Stdout :
total used free shared buffers cached
Mem: 3949 1974 1974 0 135 959
-/ buffers/cache: 879 3070
Swap: 3905 0 3905
The child process has exited , Code: 0
The above output is equivalent to executing the free -m command on the command line.
Through this simple example, we have already understood the use of child processes. Here is another example to demonstrate the use of exec.
Example 2: Using child processes to count system login times
Save the following code as last.js
var exec = require('child_process').exec,
last = exec('last | wc -l');
last.stdout.on('data', function (data) {
console.log('Stdout:' data);
});
last.on('exit', function (code) {
console.log('The child process has been closed, code: ' code);
});
Execution code:
$ node last.js
Standard output: 203
The child process has been closed, code: 0
It is the same as typing directly on the command line: last | wc - The result for l is the same.