search
HomeWeb Front-endJS TutorialHow to learn the process and child_process modules in node (detailed tutorial)

This article mainly introduces the node process and child_process module study notes. Now I share them with you and give them a reference.

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. #In Node.js every 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 The callback function is executed after the eventloop is executed
  2. process.chdir() The chdir method is used to modify the current working directory used in the Node.js application
  3. process.cwd() The current working directory of the process
  4. process.kill() Kill the process
  5. process.uncaughtException() When the application The uncaughtException event of the process object is triggered when an uncaught exception is thrown
  6. say() //方法不存在
    process.on('uncaughtException',function(err){
     console.log('捕获到一个未被处理的错误:',err);
    });
child_process

The child process is the focus of today, I also have some things that I don’t quite understand, and I hope I can communicate with you more

The background of child_process

In Node.js, there is only one thread to perform all operations. If a certain When an operation consumes a lot of CPU resources, subsequent operations 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 to be executed
  1. args array, which stores all the parameters required to run the command
  2. The options parameter is an object, used to specify the options used when starting the child process
  3. 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,当父进程不存在时也可以独立存在
    })
  4. In fact, the above is easy to understand except for the sdtio array. Let’s analyze stdio

stdio

stdio is an array used to set standard input, standard output, and error output. Personal understanding

pipe: Establish a pipe between the parent process and the child process

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

Child process code

process.stdout.write('asd')

If you put it in stdio A stream, process.stdout, process.stdin

Main process code

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]
})

Sub process code

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

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

Child process code

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

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, //保证父进程结束,子进程仍然可以运行
 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 starts a child process

    Spawn a new Node.js process and call a specified module by establishing an IPC communication channel, which allows the parent process and the child process to send information to each other
  1. The fork method returns an implicitly created ChildProcess object representing the child process
  2. After the input/output operation of the child process is completed, the child process will not automatically exit and must Explicitly exit using the process.exit() method
  3. 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('父进程接收到消息' + data)
})

child.send('hello fork')

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

Child process code

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

exec starts the child process

// 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 opens 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)
})

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

根据vue里面设置全局变量或者数据方法(详细教程)

利用jquery点击回车键实现登录效果(详细教程)

如何在vue2中设置全局变量?(详细教程)

The above is the detailed content of How to learn the process and child_process modules in node (detailed tutorial). 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
The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

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.

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

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools