Nodejs Chapter 15 (child_process)

child_process child process

Subprocess is the core API of Nodejs. If you know shell commands, it will be very helpful. Or if you like to write front-end engineering tools, it is also very useful, as well as processing CPU-intensive applications.

Create child process

Nodejs has a common API for creating child processes 7个: Sync API, otherwise it is an asynchronous API.

  1. spawn execution command
  2. exec execute command
  3. execFile executes an executable file
  4. fork creates node child process
  5. execSyncExecute commands synchronously
  6. execFileSyncExecute executable file synchronously
  7. spawnSyncExecute commands synchronously

usage

  • exec
child_process.exec(command, [options], callback)

Get nodejs version number

 exec('node -v',(err,stdout,stderr)=>{
    
    
    if(err){
    
    
        return  err
    }
    console.log(stdout.toString())
 })

options configuration items

cwd <string> 子进程的当前工作目录。
env <Object> 环境变量键值对。
encoding <string> 默认为 'utf8'。
shell <string> 用于执行命令的 shell。 在 UNIX 上默认为 '/bin/sh',在 Windows 上默认为 process.env.ComSpec。 详见 Shell Requirements 与 Default Windows Shell。
timeout <number> 默认为 0。
maxBuffer <number> stdout 或 stderr 允许的最大字节数。 默认为 200*1024。 如果超过限制,则子进程会被终止。 查看警告: maxBuffer and Unicode。
killSignal <string> | <integer> 默认为 'SIGTERM'。
uid <number> 设置该进程的用户标识。(详见 setuid(2))
gid <number> 设置该进程的组标识。(详见 setgid(2))

  • execSync

Get the node version number. If you want to execute a single shellcommand execSync, some options are the same as above.

const nodeVersion  = execSync('node -v')
console.log(nodeVersion.toString("utf-8"))

Open Google Chrome and use exec to open some software such as wx, Google QQ music, etc. The following will open Baidu and enter无痕模式

execSync("start chrome http://www.baidu.com --incognito")
  • execFile

execFile is suitable for executing executable files, such as executing a node script or shell file. Windows can write cmd scripts, and posix can write sh scripts.

Simple example

bat.cmd

Create a folder mkdir, enter the directory, write a file test.js and finally execute

echo '开始'

mkdir test 

cd ./test

echo console.log("test1232131") >test.js

echo '结束'

node test.js

Use execFile to execute this

execFile(path.resolve(process.cwd(),'./bat.cmd'),null,(err,stdout)=>{
    
    
    console.log(stdout.toString())
})

image.png

  • spawn

spawn is used to execute some information obtained in real time because spawn returns while executing the stream, and exec returns a complete buffer. The size of the buffer is 200k. If it exceeds, an error will be reported, and spawn has no upper limit.

After spawn is executed, it will throw a close event listener and return a status code. Through the status code, you can know whether the child process is executed successfully. exec can only identify the completion status through the returned buffer, which is more troublesome to identify.

//                       命令      参数  options配置
const {
    
    stdout} = spawn('netstat',['-an'],{
    
    })

//返回的数据用data事件接受
stdout.on('data',(steram)=>{
    
    
    console.log(steram.toString())
})

image.png

exec -> execFile -> spawn

exec是底层通过execFile实现 execFile底层通过spawn实现

  • fork

The scenario is suitable for a large amount of calculations, or some code that easily blocks the operation of the main process, so it is suitable for developing fork

index.js

const {
    
    fork} = require('child_process')

const testProcess = fork('./test.js')

testProcess.send('我是主进程')

testProcess.on("message",(data)=>{
    
    
    console.log('我是主进程接受消息111:',data)
})

test.js

process.on('message',(data)=>{
    
    

    console.log('子进程接受消息:',data)
})

process.send('我是子进程')

send sends information, message receives messages, and can send and receive messages to each other.

The bottom layer of fork uses IPC channel for communication.

image.png

Guess you like

Origin blog.csdn.net/qq1195566313/article/details/132797154