Introduction to NodeJS subprocesses provide important interfaces for interaction with the system. The main APIs include standard input, standard output, and standard error output.
Introduction to NodeJS sub-Processes
The node. js subprocess provides important interfaces for interaction with the system. Its main APIs include:
Interfaces for standard input, standard output, and standard error output
Child. stdin get standard input
Child. stdout get standard output
Child. stderr get standard error output
Obtain the child process PID: child. pid
Provides an important way to generate sub-processes: child_process.spawn (cmd, args = [], [options])
An important method for directly executing system commands: child_process.exec (cmd, [options], callback)
Provides a method to kill a process: child. kill (signal = 'signature ')
Example 1: obtain system memory usage using sub-Processes
Save the following code as free. js:
Copy codeThe Code is as follows:
Var spawn = require ('child _ Process'). spawn,
Free = spawn ('free', ['-m']);
// Capture the standard output and print it to the console
Free. stdout. on ('data', function (data ){
Console. log ('standard output: \ n' + data );
});
// Capture standard error output and print it to the console
Free. stderr. on ('data', function (data ){
Console. log ('standard error output: \ n' + data );
});
// Register the sub-process Close event
Free. on ('exit ', function (code, signal ){
Console. log ('sub-process exited, code: '+ code );
});
Result After code execution:
$ Node free. js
Standard output:
Total used free shared buffers cached
Mem: 3949 1974 1974 0 135 959
-/+ Buffers/cache: 879 3070
Swap: 3905 0 3905
Sub-process exited, code: 0
The above output is equivalent to executing the free-m command on the command line.
Through this simple example, we have some knowledge about the usage of sub-processes. The following is an example to demonstrate how to use exec.
Example 2: count the number of system logins using sub-Processes
Save the following code as last. js
Copy codeThe Code is as follows:
Var exec = require('child_process'cmd.exe c,
Last = exec ('Last | wc-l ');
Last. stdout. on ('data', function (data ){
Console. log ('standard output: '+ data );
});
Last. on ('exit ', function (code ){
Console. log ('sub-process closed, code: '+ code );
});
Run the Code:
$ Node last. js
Standard output: 203
The sub-process has been disabled. Code: 0
The result is the same as that of the command line: last | wc-l.