Node process and child_process module learning notes, nodechild_process
After a week of hard work, I finally understood the obscure document and prepared to share my understanding with you. I hope you can give me some comments.
Process Concept
- In Node. js, each application is an instance object of a process class.
- A process object represents an application. It is a global object that can be used to obtain attributes, methods, and events of the Node. jsy application and the user, environment, and other information that runs the program.
Several important attributes in the process
- Stdin standard input readable stream
- Stdout standard input writable stream
- Stderr standard error output stream
- Argv input parameter Array
- Env Operating System Environment Information
- Pid Application process id
Stdin and stdout
Process. stdin. on ('data', (chunk) => {process. stdout. write ('process received data' + chunk )})
Running result
Argv
console.log(process.env)
Env: enter export NODE_ENV = develop on the mac terminal.
console.log(process.env.NODE_ENV) //develop
Process Method
- Process. memoryUsage () view memory usage information
- Process. nextTick () The current eventloop is executed and the callback function is executed.
- The process. chdir () chdir method is used to modify the current working directory used in the Node. js application.
- Current working directory of process. cwd () process
- Process. kill () to kill the process
- Process. uncaughtException () The uncaughtException event that triggers the process object when an application throws an uncaptured exception
Say () // The method does not exist in process. on ('uncaughtexception ', function (err) {console. log ('caught an unprocessed error: ', err );});
Child_process
The sub-process is the focus of today's discussion. I also have some questions that I don't quite understand. I hope I can communicate with you a lot.
Background of child_process
In Node. js, only one thread executes all the operations. If an operation consumes a lot of CPU resources, subsequent operations will have to wait.
In Node. in js, A child_process module is provided, through which multiple child processes can be enabled, memory space can be shared among multiple child processes, and information exchange can be achieved through the communication between child processes.
The child_process module provides node with the ability to create any sub-processes. The node official documentation provides four methods for the child_proces module, which are mapped to the operating system to create sub-processes. But for developers, the APIs of these methods are a little different.
Child_process.exec (command [, options] [, callback]) Start
Sub-process to execute shell commands. You can use callback parameters to obtain script shell execution results.
Child_process.execfile (file [, args] [, options] [, callback])
Unlike exec, it executes not shell commands but an executable file.
Child_process.spawn (command [, args] [, options]) Only executes one shell command and does not need to obtain the execution result.
Child_process.fork (modulePath [, args] [, options]) can use node
The. js file to be executed does not need to obtain the execution result. The child process from fork must be a node process.
Spawn
Syntax: child_process.spawn (command, [args], [options])
- The parameter that the command must specify and the command to be executed
- The args array stores all the parameters required to run the command.
- The options parameter is an object used to specify the options used when sub-processes are enabled.
Const {spawn} = require ('child _ Process') const path = require ('path') let child1 = spawn ('node', ['test1. js', 'anyongchun'], {stdio: ['pipe', 'pipe', 'pipe'], // The following three element arrays will explain cwd: _ dirname, sub-process working directory env: process. env, environment variable detached: true // if it is true, it can also exist independently if the parent process does not exist })
In fact, the above is a good understanding, except sdtio array, next we will analyze stdio together
Stdio
Stdio is an array used to set standard input, standard output, and error output. Personal Understanding
Pipe: creates an pipeline between the parent process and the child process.
Master Process Code
Const path = require ('path') const {spawn} = require ('child _ Process') let p = spawn ('node', ['childs _ t. js'], {cwd: path. join (_ dirname, 'childs '), stdio: ['pipe', 'pipe', process. stderr]}) p. stdout. on ('data', (data) => {console. log (data. toString ()} // The reason why stdout is used here: the data stream of the sub-process is opposite to the data stream that is commonly understood. // stdin: Write stream, stdout, stderr: Read stream.
Sub-Process Code
process.stdout.write('asd')
If a stream is put in stdio, process. stdout, process. stdin
Master Process Code
Const {spawn} = require ('child _ Process') const path = require ('path') // If a stream is placed, it means that the parent and child processes share a stream const p = spawn ('node', ['child _ t. js'], {cwd: path. join (_ dirname, 'childs '), stdio: [process. stdin, process. stdout, process. stderr]})
Sub-Process Code
Process. stdout. write ('asd ') // The console outputs asd
Ipc
Master Process Code
const path = require('path')const { spawn } = require('child_process')let p = spawn('node', ['child_t.js'], { cwd: path.join(__dirname, 'childs'), stdio: ['ipc', 'pipe', 'pipe']})p.on('message', (msg) => { console.log(msg)})p.send('hello chhild_process')
Sub-Process Code
Process. on ('message', (msg) => {process. send ('child process' + msg)}) // child. send (message, [sendHandle]); // send a message to the child process in the parent process. // process. send (message, [sendHandle]); // send a message to the main process in the sub-process
Detached Mode
Const {spawn} = require ('child _ Process') const fs = require ('fs') const path = require ('path') let out = fs. openSync (path. join (_ dirname, 'childs/msg.txt '), 'w', 0o666) let p = spawn ('node', ['test4. js'], {detached: true, // ensure that the parent process ends and the child process can still run stdio: 'ignore', cwd: path. join (_ dirname, 'childs')}) p. unref () p. on ('close', function () {console. log ('subprocess shutdown ')}) p. on ('exit ', function () {console. log ('sub-process exited ')}) p. on ('error', function (err) {console. log ('sub-process 1 failed to enable '+ err )})
Fork starts a sub-process
- A new Node. js process is derived and an IPC communication channel is established to call a specified module. This channel allows Parent and Child processes to send messages to each other.
- The fork method returns an implicitly created ChildProcess object representing the child process.
- After the sub-process input/output operations are completed, the sub-process does not automatically exit. You must use the process. exit () method to exit explicitly.
Sub-Process Code
Const {fork} = require ('child _ Process') const path = require ('path') let child = fork (path. join (_ dirname, 'childs/fork1.js') child. on ('message', (data) => {console. log ('parent process received message' + data)}) child. send ('Hello fork') child. on ('error', (err) => {console. error (err )})
Sub-Process Code
Process. on ('message', (m, setHandle) => {console. log ('subprocess received message' + m) process. send (m) // sendHandle is a net. socket or net. server Object })
Exec enable sub-process
// Exec synchronously executes a shell command let {exec} = require ('child _ Process') let path = require ('path') // It is used to execute commands using shell, synchronization Method let p1 = exec ('node exec. js a B C', {cwd: path. join (_ dirname, 'childs')}, function (err, stdout, stderr) {console. log (stdout )})
ExecFile
let { execFile } = require('child_process')let path = require('path')let p1 = execFile('node', ['exec.js', 'a', 'b', 'c'], { cwd: path.join(__dirname, 'childs')}, function(err, stdout, stderr) { console.log(stdout)})
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.