child_process
Child_process is used to create child processes. Node and its derived child processes build stdin(standard input), STdout (standard output), and stderr(standard error) pipes. Spawn, child_process.fork, child_process.exec, and child_process.execFile all return ChildProcess instances. ChildProcess instances implement the EventEmitter API, which allows you to add event callbacks to ChildProcess instances. Processes can communicate with each other through an event message system.
child_process.spawn
Start a child process to execute a command. Spawn (Command: string, args: ReadonlyArray
, options: SpawnOptions): ChildProcess
- Command: the command to run
- Args, the argument to run the command, is an array of strings
- The options and configuration items
- Options. CWD the working directory of the child process
- Options. env environment variables. Use key and value to configure environment variables
- , etc.
- Return the value ChildProcess, which returns an instance of ChildProcess
/ / case
const { spawn, spawnSync } = require('child_process')
const path = require('path')
const cp = spawn('ls'['-a'] and {cwd: path.resolve(__dirname, '.. /Movies')
})
cp.stdout.on('data'.(data) = > {
console.log('Child process output :'${data}`)
})
cp.on('exit'.(code, signal) = > {
console.log('Child process exits :'.`code ${code} and signal ${signal}`)})Copy the code
Output result:
By default, the ChildProcess’s standard input, standard output, and standard error are redirected to the corresponding subprocess.stdin, subprocess.stdout, and subprocess.stderr streams on the ChildProcess object. You can set options. Stdio: inherit to the parent process,
const { spawn, spawnSync } = require('child_process')
const path = require('path')
const cp = spawn('ls'['-a'] and {cwd: path.resolve(__dirname, '.. /Movies'),
stdio: 'inherit'
})
Copy the code
child_process.spawnSync
Synchronous version of child_process.spawn. Child_process. spawnSync Returns Object. Object includes pid(child pid), STdout (standard output), stderr(standard error), and so on. The difference is that this function does not return until the child process is completely closed.
const { spawnSync } = require('child_process')
const path = require('path')
const obj = spawnSync('ls'['-a'] and {cwd: path.resolve(__dirname, '.. /Movies')})console.log('pid'.`${obj.pid}`)
console.log('stdout'.`${obj.stdout}`)
Copy the code
child_process.exec
Create a derived shell from which you can then execute commands. Exec implements function overloading. The second argument can be a configuration item or a callback. If the second parameter is the configuration item, the third parameter is the callback.
const { exec } = require('child_process')
const path = require('path')
exec('ls'.(error, stdout, stderr) = > {
if (error) {
console.error('error:', error);
return;
}
console.log('stdout: ' + stdout);
console.log('stderr: ' + stderr);
})
// The second argument can be a configuration item
exec('ls -a', { cwd: path.resolve(__dirname, '.. /Movies'),},(error, stdout, stderr) = > {
if (error) {
console.error('error:', error);
return;
}
console.log('stdout: ' + stdout);
console.log('stderr: ' + stderr);
})
Copy the code
The three arguments to callback are the error instance (error equals null if the execution succeeds), stdout standard output, and stderr standard error.
child_process.execSync
The synchronized version of child_process.exec. The child_process.execSync method returns standard output, the difference being that it does not return until the child process is completely shut down.
const { execSync } = require('child_process')
const path = require('path')
const stdout = execSync('ls -a', { cwd: path.resolve(__dirname, '.. /Movies')})console.log('stdout:'.`${stdout}`)
Copy the code
Difference between child_process.exec and child_process.spawn
- spawn
- No derived shells are created
- Streams the data generated by the child process
- There is no data size limit
- exec
- A derived shell is created
- The maximum data transmission is 200KB
- Data is cached and transferred after the process is shut down
Spawn is suitable for large, long time data transfers. Exec is suitable for situations where multiple, small quantities are needed.
child_process.fork
Child_process.fork, used to run the module in the child process. child_process.fork(modulePath [, args] [, options])
- ModulePath, the address of the module that needs to run in the child process
- Args, string argument list
- The options configuration items
- ExecPath, used to create an executable file for the child process. You can configure this parameter to specify different versions of Node to create child processes.
- ExecArgv, a list of string arguments passed to the executable.
- Silent, standard output of child process, whether inherit from parent process. The default is false for inheritance. If set to true pipe directly to child.stdin, child.stdout, etc.
- Stdio, used to configure the pipe between the parent and child processes
// The child process code
console.log('I'm a child process')
Copy the code
const { fork } = require('child_process')
const { resolve } = require('path')
// I am the child process
fork(resolve(__dirname, './cp.js'), {
silent: false
})
// No print
fork(resolve(__dirname, './cp.js'), {
silent: true
})
Copy the code
const { fork } = require('child_process')
const { resolve } = require('path')
const cp = fork(resolve(__dirname, './cp.js'), {
silent: true
})
cp.stdout.on('data'.function (data) {
// stdout outputs: I am a child process
console.log('stdout outputs: '.`${data}`)})Copy the code
With the stdout attribute, you can get the output of the child process
child_process.execFile
Child_process. execFile does not create a derived shell. Be more efficient than Exec. child_process.execFile(file[, args] [, options] [, callback])
- File, can be the name of the execution file, or the path.
const { execFile } = require('child_process')
const { resolve } = require('path')
execFile('node', [resolve(__dirname, './cp.js')].(err, stdout, stderr) = > {
if (err) {
throw err
}
console.log(`stdout: ${stdout}`)})Copy the code
Difference between child_process.exec and child_process.execFile
Exec is implemented internally by calling execFile. Internally, execFile is implemented by calling spawn.
The event
Many events can be listened on a ChildProcess instance
- Close, triggered when the child process’s STDIO stream is closed
- Disconnect, triggered when the parent process manually calls the child.disconnect function
- Error, triggered when an error occurs
- Exit, triggered when the child process exits
- Message, triggered when a child process uses the process.send function to pass a message
const { fork } = require('child_process');
const cp = fork('./cp.js')
cp.on('close'.(code, signal) = > {
console.log('close event: ', code, signal);
})
cp.on('disconnect'.() = > {
console.log('the disconnect events... ');
})
cp.on('error'.(code, signal) = > {
console.log('Error event:', code, signal);
})
cp.on('exit'.(code, signal) = > {
console.log('Exit event:', code, signal);
})
cp.on('message'.(val) = > {
console.log('Message event:', val);
})
Copy the code
Communication between processes
After a child process is created, an IPC channel is created between the parent process and child process. The parent process communicates with the child process through Message and Send.
/ / the parent process
const { fork } = require('child_process');
const cp = fork('./cp.js')
cp.on('message'.(msg) = > {
console.log('message: ' + JSON.stringify(msg))
})
Copy the code
/ / the child process
process.send({
msg: 'I'm a child process'
})
Copy the code
The parent process can also send messages to the child process using cp.send
/ / the parent process
const { fork } = require('child_process');
const cp = fork('./cp.js')
cp.send({
msg: 'I'm the parent process'
})
Copy the code
reference
- Node. Js v16.8.0 document
- Node.js Child Processes: Everything you need to know
- exec vs execFile nodeJs
- Node.js Spawn vs. Execute
- Nodejs: How to play child_process
- Learn more about processes and threads in Node.js
- Node.js Process module learning guide
- Play with node child process – child_process