Home Web Front-end JS Tutorial Teach you how to use node.js to create a child process

Teach you how to use node.js to create a child process

Dec 11, 2017 am 09:35 AM
javascript node.js create

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 + " 执行。" );
Copy after login


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(&#39;node node-childPro.js &#39;+i,
 // 回调函数 子进程的输出以回调函数参数的形式返回
 function (error, stdout, stderr) {
  if (error) {
  console.log(error.stack);
  console.log(&#39;Error code: &#39; + error.code);
  console.log(&#39;Signal received: &#39; + error.signal);
  }
  console.log(&#39;stdout: &#39; + stdout);
  console.log(&#39;stderr: &#39; + stderr);
 });
 childProcess.on(&#39;exit&#39;, function (code) {
 console.log(&#39;子进程已退出,退出码 &#39; + code);
 });
}
Copy after login


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:
Copy after login


##spawn() method

Create a new node-childPro-spawn.js in the node-childProcess file, with the following code:


const fs = require(&#39;fs&#39;);
const child_process = require(&#39;child_process&#39;);
 for(var i=0; i<3; i++) {
 var childProcess = child_process.spawn(&#39;node&#39;, [&#39;node-childPro-spawn.js&#39;, i]);  
 childProcess.stdout.on(&#39;data&#39;, function (data) {
 console.log(&#39;stdout: &#39; + data);
 });
childProcess.stderr.on(&#39;data&#39;, function (data) {
 console.log(&#39;stderr: &#39; + data);
 });
 childProcess.on(&#39;close&#39;, function (code) {
 console.log(&#39;子进程已退出,退出码 &#39;+code);
 });
}
Copy after login


The terminal execution code results are as follows:


G:\node\node-childProcess> node node-childPro-spawn.js
stdout: 进程 0 执行。
子进程已退出,退出码 0
stdout: 进程 1 执行。
stdout: 进程 2 执行。
子进程已退出,退出码 0
子进程已退出,退出码 0
Copy after login


##fork() methodCreate a new node-childPro-fork.js in the node-childProcess file, with the following code:

##
const fs = require(&#39;fs&#39;);
const child_process = require(&#39;child_process&#39;);
 for(var i=0; i<3; i++) {
 var childProcess = child_process.fork("node-childPro.js", [i]); 
 childProcess.on(&#39;close&#39;, function (code) {
 console.log(&#39;子进程已退出,退出码 &#39; + code);
 });
}
Copy after login


Terminal execution code results are as follows:

G:\node\node-childProcess> node node-childPro-fork.js
进程 0 执行。
进程 1 执行。
子进程已退出,退出码 0
进程 2 执行。
子进程已退出,退出码 0
子进程已退出,退出码 0
Copy after login



#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


3. After the sub-thread starts executing, spawn begins to continuously return data from the sub-process to the main process (application scenarios such as "system monitoring" ”)


4.spawn does not support the callback function. It sends data to the main process through a stream, thus realizing data exchange between multiple processes


5.fork() is a special case of spawn(), used to spawn Node processes. In addition to all the methods of a normal ChildProcess instance, the returned object also has built-in communication channels.


Have you learned it? Hurry up and give it a try.

Related recommendations:

PHP and Node.js

Node.js’s brief introduction to asynchronous flow control

Node.JS related knowledge

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!

Statement of this Website
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to create pixel art in GIMP How to create pixel art in GIMP Feb 19, 2024 pm 03:24 PM

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

How to create a family with Gree+ How to create a family with Gree+ Mar 01, 2024 pm 12:40 PM

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.

How to Create a Contact Poster for Your iPhone How to Create a Contact Poster for Your iPhone Mar 02, 2024 am 11:30 AM

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

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

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

A first look at Django: Create your first Django project using the command line A first look at Django: Create your first Django project using the command line Feb 19, 2024 am 09:56 AM

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

How to create mdf file How to create mdf file Feb 18, 2024 pm 01:36 PM

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

How to create a folder on Realme Phone? How to create a folder on Realme Phone? Mar 23, 2024 pm 02:30 PM

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.

How to create a WeChat group? How to create a WeChat group How to create a WeChat group? How to create a WeChat group Mar 06, 2024 pm 02:55 PM

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【

See all articles