search
HomeWeb Front-endJS TutorialDetailed explanation of the use of process and child_process

This time I will bring you a detailed explanation of the use of process and child_process. What are the precautions when using process and child_process? Here are practical cases, let’s take a look.

After struggling with the process for a week, I finally understood the obscure and difficult document, and am ready to share my understanding with everyone. I also hope that everyone can point out some opinions

Process The concept of

  1. InNode.jseach application is an instance object of the process class.

  2. Use the process object to represent the application. This is a global object through which you can obtain the properties of the Node.jsy application and the user and environment running the program. methods and events.

Several important attributes 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 operating system environment information

  6. pid application process id

stdin and stdout

process.stdin.on('data', (chunk) => {
 process.stdout.write('进程接收到数据' + chunk)
})

Run result

argv

console.log(process.env)

##env: Enter export NODE_ENV=develop

console.log(process.env.NODE_ENV) //develop
# in the mac terminal ##Methods of process

    process.memoryUsage() View memory usage information
  1. process.nextTick() Current Execution after eventloop is executed
  2. Callback function

  3. process.chdir() The chdir method is used to modify the current working directory used in Node.js applications
  4. process.cwd() The current working directory of the process
  5. process.kill() Kill the process
  6. process. uncaught
  7. Exception

    () Triggers the uncaughtException event of the process object when the application throws an uncaught exception

    say() //方法不存在
    process.on('uncaughtException',function(err){
     console.log('捕获到一个未被处理的错误:',err);
    });
child_process

Child process is the focus of today’s talk. I also don’t understand some of it. I hope I can communicate with you more.

The background of child_process

In Node In .js, only one thread performs all operations. If an operation requires a large amount of CPU resources, subsequent operations will need to wait.

In Node.js, a child_process module is provided, through which multiple child processes can be started, memory space can be shared between multiple child processes, and information exchange can be achieved through mutual communication of child processes.

The child_process module gives node the ability to create child processes at will. The official document of node gives four methods for the child_proces module. Mapping to the operating system actually creates child processes. But for developers only, the APIs of these methods are a little different

child_process.exec(command[, options][, callback]) starts the

child process to execute the shell command, which can be done through the callback parameter Get the script shell execution result


child_process.execfile(file[, args][, options][, callback])

Different from the exec type, it does not execute a shell command but an executable File


child_process.spawn(command[, args][, options]) only executes a shell command and does not need to obtain the execution results

child_process.fork(modulePath[, args][, options] ]) You can use node

to execute the .js file, and there is no need to obtain the execution results. The child process coming out of fork must be the node process


spawn

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

    command Parameters that must be specified, specify the command that needs to be executed
  1. args array, which stores all the parameters required to run the command
  2. options 参数为一个对象,用于指定开启子进程时使用的选项

const { spawn } = require('child_process')
const path = require('path')
let child1 = spawn('node', ['test1.js', 'yanyongchao'], {
 stdio: ['pipe', 'pipe', 'pipe'], // 三个元素数组 下面会详解
 cwd: dirname, 子进程工作目录
 env: process.env, 环境变量
 detached: true // 如果为true,当父进程不存在时也可以独立存在
})

其实上面都好理解除了sdtio数组,下面来一起分析stdio

stdio

stdio是一个数组,用来设置标准输入,标准输出,错误输出。个人理解

pipe:父进程和子进程之间建立一个管道

主进程代码

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原因: 子进程的数据流与常规理解的数据流方向相反,
// stdin:写入流,stdout、stderr:读取流。

子进程代码

process.stdout.write('asd')

如果在stdio中放一个流,process.stdout,process.stdin

主进程代码

const { spawn } = require('child_process')
const path = require('path')
// 如果放的是一个流,则意味着父进程和子进程共享一个流
const p = spawn('node', ['child_t.js'], {
 cwd: path.join(dirname, 'childs'),
 stdio: [process.stdin, process.stdout, process.stderr]
})

子进程代码

process.stdout.write('asd') //控制台会输出asd

ipc

主进程代码

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')

子进程代码

process.on('message', (msg) => {
 process.send('子进程' + msg)
})
// child.send(message,[sendHandle]);//在父进程中向子进程发送消息
// process.send(message,[sendHandle]);//在子进程中向主进程发送消息

detached模式

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, //保证父进程结束,子进程仍然可以运行
 stdio: 'ignore',
 cwd: path.join(dirname, 'childs')
})
p.unref()
p.on('close', function() {
 console.log('子进程关闭')
})
p.on('exit', function() {
 console.log('子进程退出')
})
p.on('error', function(err) {
 console.log('子进程1开启失败' + err)
})

fork开启一个子进程

  1. 衍生一个新的 Node.js 进程,并通过建立一个 IPC 通讯通道来调用一个指定的模块,该通道允许父进程与子进程之间相互发送信息

  2. fork方法返回一个隐式创建的代表子进程的ChildProcess对象

  3. 子进程的输入/输出操作执行完毕后,子进程不会自动退出,必须使用process.exit()方法显式退出

子进程代码

const { fork } = require('child_process')
const path = require('path')
let child = fork(path.join(dirname, 'childs/fork1.js'))
child.on('message', (data) => {
 console.log('父进程接收到消息' + data)
})
child.send('hello fork')
child.on('error', (err) => {
 console.error(err)
})

子进程代码

process.on('message', (m, setHandle) => {
 console.log('子进程接收到消息' + m)
 process.send(m) //sendHandle是一个 net.Socket 或 net.Server 对象
})

exec开启子进程

// exec同步执行一个shell命令
let { exec } = require('child_process')
let path = require('path')
// 用于使用shell执行命令, 同步方法
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)
})

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

Vue打包之后文件路径出错如何处理

vue打包后字体和图片资源失效如何处理

The above is the detailed content of Detailed explanation of the use of process and child_process. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function