After a week, I finally understood the obscure document and prepared to share my understanding with you. I also hope you can point out some opinions

Concept of process

  1. In Node.js each application is an instance object of a process class.
  2. The application is represented by a Process object, which is a global object that gets properties, methods, and events for the Node.jsy application and various information about the user, environment, and so on that runs it.

Several important properties in the process

  1. Stdin standard input readable stream
  2. Stdout Standard input writable stream
  3. Stderr Standard error output stream
  4. Argv terminal input parameter array
  5. Env Specifies the operating system environment
  6. Pid Indicates the ID of an application process

Stdin and stdout

process.stdin.on('data', (chunk) => {
  process.stdout.write('Process receives data' + chunk)
})
Copy the code

The results

argv

console.log(process.env)
Copy the code

Env: On the MAC terminal, run export NODE_ENV=develop

console.log(process.env.NODE_ENV) //develop
Copy the code

Process methods

  1. Process.memoryusage () displays memoryUsage information
  2. Process.nexttick () Executes the callback function when the eventloop completes
  3. The process.chdir() chdir method is used to modify the current working directory used in node.js applications
  4. The current working directory of process.cwd()
  5. Process.kill () kills the process
  6. Process. UncaughtException () when the application throws an exception is not caught trigger a process object uncaughtException events
Say () // method does not exist process.on('uncaughtException'.function(err){
  console.log('An unhandled error was caught :',err);
});
Copy the code

child_process

Subprocesses are the focus of today’s talk, and I don’t understand some of them, so I hope to share more with you

Context in which child_process appears

In Node.js, only one thread performs all operations, and if an operation consumes a lot of CPU resources, subsequent operations have to wait.

Node.js provides a child_process module that enables multiple child processes to share memory space and exchange information by communicating with each other.

spawn

Syntax: child_process.spawn(command, [args], [options])

  1. Command Specifies the parameter that must be specified to run the command
  2. The args array holds all the parameters needed to run the command
  3. The options argument is an object that specifies the options to use when starting the child process
const { spawn } = require('child_process')
const path = require('path')

let child1 = spawn('node'['test1.js'.'yanyongchao'], {
    stdio: ['pipe'.'pipe'.'pipe'[detached], // Element array: __dirname, child working directory env: process.env, environment variable detached:true/ / if it istrue, can exist independently when the parent process does not exist})Copy the code

All of this is easy to understand except for sdTIO array, so let’s analyze STDIO

stdio

Stdio is an array that sets standard input, standard output, and error output. Personal understanding

Pipe: Establishes a pipe between parent and child processes

Main 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 ())}) // Stdout is used here because the data flow of the child process is in the opposite direction of the conventional understanding of data flow, // stdin: write to the stream, stdout, stderr: read the stream.Copy the code

Child process code

process.stdout.write('asd')
Copy the code

If put a stream in the stdio, process. Stdout, process. The stdin

Main process code

const { spawn } = require('child_process')
const path = require('path'Const p = spawn() const p = spawn() const p = spawn()'node'['child_t.js'], {
  cwd: path.join(__dirname, 'childs'),
  stdio: [process.stdin, process.stdout, process.stderr]
})
Copy the code

Child process code

process.stdout.write('asd'// The console will output asDCopy the code

ipc

Main 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')
Copy the code

Child process code

process.on('message', (msg) => {
  process.send('Child process'+ msg) }) // child.send(message,[sendHandle]); // Send (message,[sendHandle]); // Send (message,[sendHandle]); // Send a message to the main process in the child processCopy the code

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// To ensure that the parent process is finished, the child process can still run stdio:'ignore',
  cwd: path.join(__dirname, 'childs')
})

p.unref()

p.on('close'.function() {
  console.log('Child process closed')
})

p.on('exit'.function() {
  console.log('Child process exits')
})

p.on('error'.function(err) {
  console.log('Child process 1 failed to start' + err)
})
Copy the code

Fork starts a child process

  1. Spawn a new Node.js process and invoke a specified module by setting up an IPC communication channel that allows parent and child processes to send messages to each other
  2. The fork method returns an implicitly created ChildProcess object representing the ChildProcess
  3. The child process does not exit automatically after the input/output operation is completed, and must exit explicitly using the process.exit() method

Child 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 receives message' + data)
})

child.send('hello fork')

child.on('error', (err) => {
  console.error(err)
})
Copy the code

Child process code

process.on('message', (m, setHandle) => {
  console.log('Child process receives message'+ m) process.send(m) //sendHandle is a net.socket or net.server object})Copy the code

Exec starts the child process

// execExecute a shell command synchronouslylet { exec } = require('child_process')
let path = require('path') // Used to execute commands using the shell and synchronize methodslet p1 = exec('node exec.js a b c', {cwd: path.join(__dirname, 'childs')}, function(err, stdout, stderr) {
  console.log(stdout)
})
Copy the code

ExecFile Starts the child process

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)
})
Copy the code