NodeJs concise tutorial will start from scratch to learn about NodeJs and help JS developers build a full stack development technology stack!
Focus on getting more NodeJs articles
This article is the eighth chapter of NodeJs concise tutorial, which will introduce the basic operation of NodeJs sub-process module.
The child_process module provides the ability to derive child processes in a similar but different way than popen(3).
Although NodeJs JS threads are single-threaded, can not use multi-core CPU, and can not perform CPU-intensive tasks, but through the form of derived sub-processes plus IPC (interprocess communication), can make full use of multi-core CPU.
spawn
spawn
ExecutableDesignated commands
,spawn
The prototype of the function is as follows:child_process.spawn(command[,args][,options])
- Command < string > command to execute
- Args < string []> parameter list passed to the command
-
Options < Object > Additional Options
- CWD < string > subprocess workdir
- Env < Object > child process environment variable
const { spawn } = require('child_process'); const ls = spawn('ls', ['-lh', '/usr']); // Command Configuration ls.stdout.on('data', (data) => { // Standard output for listening for command execution console.log(`stdout: ${data}`); }); ls.stderr.on('data', (data) => { // Standard error output for listening for command execution console.log(`stderr: ${data}`); }); ls.on('close', (code) => { // Listener child process exit console.log(`Subprocess exit, using exit code ${code}`); });
The above routine output (different machine output may be different)
stdout: total 0 drwxr-xr-x 970 root wheel 30K 7 19 23:00 bin drwxr-xr-x 306 root wheel 9.6K 7 12 22:35 lib drwxr-xr-x 249 root wheel 7.8K 7 19 23:00 libexec drwxr-xr-x 15 root wheel 480B 4 1 14:15 local drwxr-xr-x 239 root wheel 7.5K 7 12 22:35 sbin drwxr-xr-x 46 root wheel 1.4K 9 21 2018 share drwxr-xr-x 5 root wheel 160B 9 21 2018 standalone //Subprocess exit, using exit code 0
exec
Exc can also execute a specified command, unlike span, where the execution result is notified by a callback, and span is notified by an event. The prototype of exec function is as follows:
exec(command[,options][,callback])
- Command < string > command parameters are separated by spaces
-
Options < Object > Additional Options
- CWD < string > subprocess workdir
- Env < Object > child process environment variable
- Timeout < number > subprocess execution timeout
-
Callback < Function > Result Callback
- Error < Error > Execution error (not the error output of the child process)
- Stdout < string | Buffer > standard output for subprocesses
- Stderr < string | Buffer > standard error output for subprocesses
const exec = require('child_process').exec; exec('ls -lh /usr',function(err,stdout,stderr) { if(err) { console.log('Execution error', err); } console.log('stdout', stdout); console.log('stderr', stderr); });
Output of the above routine
stdout: total 0 drwxr-xr-x 970 root wheel 30K 7 19 23:00 bin drwxr-xr-x 306 root wheel 9.6K 7 12 22:35 lib drwxr-xr-x 249 root wheel 7.8K 7 19 23:00 libexec drwxr-xr-x 15 root wheel 480B 4 1 14:15 local drwxr-xr-x 239 root wheel 7.5K 7 12 22:35 sbin drwxr-xr-x 46 root wheel 1.4K 9 21 2018 share drwxr-xr-x 5 root wheel 160B 9 21 2018 standalone //Subprocess exit, using exit code 0
execFile
ExcFile is similar to exec, but does not derive a shell by default. Instead, the specified execFile is directly derived as a new process, making it slightly more efficient than exec.
Support the same options as exec. Because there is no derived shell, I/O redirection and file wildcards are not supported. ExcFile prototype:
execFile(file[,args][,options][,callback])
- File < string > command to execute or executable file path
- Args < string []> Array parameter list
-
Options < Object > Additional Options
- CWD < string > subprocess workdir
- Env < Object > child process environment variable
- Timeout < number > subprocess execution timeout
-
Callback < Function > Result Callback
- Error < Error > Execution error (not the error output of the child process)
- Stdout < string | Buffer > standard output for subprocesses
- Stderr < string | Buffer > standard error output for subprocesses
const execFile = require('child_process').execFile; execFile('ls', ['--version'], function(error, stdout, stderr) { if(err) { console.log('Execution error', err); } console.log('stdout', stdout); console.log('stderr', stderr); });
The output of the above routine is the same as exec
fork
Fork is a special case of span that is dedicated to deriving new NodeJs processes. Spawn can spawn any process. The prototype of fork method is as follows:
fork(modulePath[,args][,options])
- ModulePath < string > JS path to execute
- Args < string []> Array parameter list
-
Options < Object > Additional Options
- workdir of CWD < string > subprocess
- Env < Object > environment variable
- Silent < Boolean > If true, the stdin, stdout and stderr of the child process will be transported to the parent process, otherwise they will inherit from the parent process. Default false
b.js
const fork = require('child_process').fork; const child = fork('./a.js',{silent:true}); // When silent is true, it can listen for standard output and standard error output of subprocesses. child.stdout.on('data',function(data){ // Standard output of listener subprocesses console.log('child stdout', data.toString('utf8')); }); child.stderr.on('data', function(data){ // Standard error output for listener subprocesses console.log('child stderr', data.toString('utf8')); }); child.on('close', function(){ console.log('child exit'); });
a.js
console.log('I'm a child process');
The terminal executes node b.js, and the above routine output:
child stdout I am a child process child exit
epilogue
This is the end of the introduction of the sub-process module, usually using span and execFile. If you have any questions, please do not hesitate to share them.