Teach you how to use node.js to create a child process
There is a lot of knowledge related to multi-process. It was also mentioned when writing the Process module, but I found that it is not too difficult to understand. This article mainly introduces you to the relevant information on how to create a child process using node.js. Friends who need it can refer to it. I hope it can help you.
Preface
Node itself is a single process and uses driver mode to handle concurrency. In order to solve the waste of resources of a single process on a multi-core CPU, Node provides the cluster and child_process modules to create multiple child processes.
Node.js is single-threaded, which is a waste for multi-processor machines. How can it be used? So the child_process module appeared. The child_process module can spawn, fork, and perform work on other processes.
The child_process module provides a new class ChildProcess, which can be used as a representation of accessing the child process from the parent process. The Process module is also a ChildProcess object. When you access process from the parent module, it is the parent ChildProcess object. When you access Process from the child process, it is the ChildProcess object
Understanding an object is nothing more than events, methods, and properties. The same goes for ChildProcess.
Each child process always has three stream objects: child.stdin, child.stdout, child.stderr. They may share the stdio stream of the parent process.
Here we first introduce how to operate the child process using the three methods of exec, spawn, and fork in the child_process module.
Create the node-childProcess file and create the node-childPro.js file in it.
One line of code is as follows:
console.log("进程 " + process.argv[2] + " 执行。" ); //换成下面的查看process.argv //console.log("进程 " + process.argv + " 执行。" );
exec() method
Create a new node-childPro-exec.js file in the node-childProcess file, with the following code:
const fs = require('fs'); const child_process = require('child_process'); for (var i = 0; i < 3; i++) { //这里有空格请注意。分别代表node路径 node-childPro.js路径 i第几个进程。 node-childPro.js中的process.argv可以获取这些信息值 var childProcess = child_process.exec('node node-childPro.js '+i, // 回调函数 子进程的输出以回调函数参数的形式返回 function (error, stdout, stderr) { if (error) { console.log(error.stack); console.log('Error code: ' + error.code); console.log('Signal received: ' + error.signal); } console.log('stdout: ' + stdout); console.log('stderr: ' + stderr); }); childProcess.on('exit', function (code) { console.log('子进程已退出,退出码 ' + code); }); }
The terminal execution code results are as follows:
G:\node\node-childProcess> node node-childPro-exec.js 子进程已退出,退出码 0 stdout: 进程 0 执行。 stderr: 子进程已退出,退出码 0 stdout: 进程 1 执行。 stderr: 子进程已退出,退出码 0 stdout: 进程 2 执行。 stderr:
##spawn() method
Create a new node-childPro-spawn.js in the node-childProcess file, with the following code:const fs = require('fs'); const child_process = require('child_process'); for(var i=0; i<3; i++) { var childProcess = child_process.spawn('node', ['node-childPro-spawn.js', i]); childProcess.stdout.on('data', function (data) { console.log('stdout: ' + data); }); childProcess.stderr.on('data', function (data) { console.log('stderr: ' + data); }); childProcess.on('close', function (code) { console.log('子进程已退出,退出码 '+code); }); }
G:\node\node-childProcess> node node-childPro-spawn.js stdout: 进程 0 执行。 子进程已退出,退出码 0 stdout: 进程 1 执行。 stdout: 进程 2 执行。 子进程已退出,退出码 0 子进程已退出,退出码 0
##fork() methodCreate a new node-childPro-fork.js in the node-childProcess file, with the following code:
##const fs = require('fs'); const child_process = require('child_process'); for(var i=0; i<3; i++) { var childProcess = child_process.fork("node-childPro.js", [i]); childProcess.on('close', function (code) { console.log('子进程已退出,退出码 ' + code); }); }
Terminal execution code results are as follows:
G:\node\node-childProcess> node node-childPro-fork.js 进程 0 执行。 进程 1 执行。 子进程已退出,退出码 0 进程 2 执行。 子进程已退出,退出码 0 子进程已退出,退出码 0
#About exec, spawn, fork
1. The exec function is a friendly encapsulation of spawn. It adds Shell command parsing and can directly embed complex commands
2. The exec function caches the output of the child process and Return the output of the sub-process in the form of callback function parameters
Have you learned it? Hurry up and give it a try.
Related recommendations:
PHP and Node.jsNode.js’s brief introduction to asynchronous flow control
The above is the detailed content of Teach you how to use node.js to create a child process. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

This article will interest you if you are interested in using GIMP for pixel art creation on Windows. GIMP is a well-known graphics editing software that is not only free and open source, but also helps users create beautiful images and designs easily. In addition to being suitable for beginners and professional designers alike, GIMP can also be used to create pixel art, a form of digital art that utilizes pixels as the only building blocks for drawing and creating. How to Create Pixel Art in GIMP Here are the main steps to create pixel pictures using GIMP on a Windows PC: Download and install GIMP, then launch the application. Create a new image. Resize width and height. Select the pencil tool. Set the brush type to pixels. set up

Many friends expressed that they want to know how to create a family in Gree+ software. Here is the operation method for you. Friends who want to know more, come and take a look with me. First, open the Gree+ software on your mobile phone and log in. Then, in the options bar at the bottom of the page, click the "My" option on the far right to enter the personal account page. 2. After coming to my page, there is a "Create Family" option under "Family". After finding it, click on it to enter. 3. Next jump to the page to create a family, enter the family name to be set in the input box according to the prompts, and click the "Save" button in the upper right corner after entering it. 4. Finally, a "save successfully" prompt will pop up at the bottom of the page, indicating that the family has been successfully created.

In iOS17, Apple has added a contact poster feature to its commonly used Phone and Contacts apps. This feature allows users to set personalized posters for each contact, making the address book more visual and personal. Contact posters can help users identify and locate specific contacts more quickly, improving user experience. Through this feature, users can add specific pictures or logos to each contact according to their preferences and needs, making the address book interface more vivid. Apple in iOS17 provides iPhone users with a novel way to express themselves, and added a personalizable contact poster. The Contact Poster feature allows you to display unique, personalized content when calling other iPhone users. you

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Start the journey of Django project: start from the command line and create your first Django project. Django is a powerful and flexible web application framework. It is based on Python and provides many tools and functions needed to develop web applications. This article will lead you to create your first Django project starting from the command line. Before starting, make sure you have Python and Django installed. Step 1: Create the project directory First, open the command line window and create a new directory

MDF file is a common database file format and it is one of the main files of Microsoft SQL Server database. In database management systems, MDF files are used to save the main data of the database, including tables, indexes, stored procedures, etc. Creating an MDF file is one of the key steps in creating a database. Some common methods will be introduced below. Using SQLServerManagementStudio(SSMS)SQLServerManag

Title: Realme Phone Beginner’s Guide: How to Create Folders on Realme Phone? In today's society, mobile phones have become an indispensable tool in people's lives. As a popular smartphone brand, Realme Phone is loved by users for its simple and practical operating system. In the process of using Realme phones, many people may encounter situations where they need to organize files and applications on their phones, and creating folders is an effective way. This article will introduce how to create folders on Realme phones to help users better manage their phone content. No.

WeChat is a mainstream chat tool. Users can communicate with friends through WeChat in a richer form. Sometimes, due to some circumstances, we need to create groups to quickly circle people, such as common classmate groups, class groups, family groups, company groups, micro-business groups, etc. Let’s learn how to create a WeChat group! How to create a WeChat group? The first method to create a WeChat group: 1. Click [+] in the upper right corner of the WeChat interface; 2. Click [Start Group Chat]; 3. Select the communication friends you want to initiate a group chat with, and click the upper right corner after selecting [Complete]; 4. Click [···] in the upper right corner of the group chat to enter the group chat setting interface; 5. After opening the group chat setting interface, click [Group Chat Name] to set the group name; 6. Click [+] or【
