Home  >  Article  >  Web Front-end  >  node.js fun process instance

node.js fun process instance

小云云
小云云Original
2018-03-17 16:39:121354browse


This article mainly shares with you node.js play process examples. node provides the child_process module. We then save the classic sample code as a worker.js file, as follows:

let http=require('http');
http.createServer(function (req,res) {
    res.writeHead(200,{'Content-Type':"text/plain"});
    res.end('hello world')
}).listen(Math.round((1+Math.random())*1000),'127.0.0.1');

Save the following code as master.js and start it through node master.js:

let fork=require('child_process').fork;
let cpus=require(&#39;os&#39;).cpus();for(let i=0;i<cpus.length;i++){    fork(&#39;./work.js&#39;);
}

Check the number of processes through ps aux|grep worker.js under *nix systems.
This is the master-worker mode, also known as the master-slave mode.
node.js fun process instanceThe processes copied by fork are independent. This process has an independent and brand-new V8 instance. Forking a process is expensive.

9.2.1 Create sub-process

The sub-process in the new version of node also has synchronous sub-process and asynchronous sub-process, here refers to the asynchronous sub-process
- spawn(): Start a child process
- exec(): Start a child process. The difference from spawn is that it has a callback function
- execFile(): Start a child process to execute the executable file
- fork(): Similar to spawn, the difference is that it only needs to specify the js file to create a node sub-process.

The difference between spawn and exec and execFile is that the timeout attribute can be specified when the latter two are created to set the timeout. time, the child process can be killed after the time is up.
The difference between exec and execFile is that exec is suitable for executing existing commands, and execFile is suitable for executing files.

let cp=require(&#39;child_process&#39;);
cp.spawn(&#39;node&#39;,[&#39;worker.js&#39;]);//没有回调函数cp.exec(&#39;node worker.js&#39;,function (err,stdout,stderr) {});
cp.execFile(&#39;worker.js&#39;,function (err,stdout,stderr) {});
cp.fork(&#39;./worker.js&#39;);

9.2.2 Inter-process communication

parent.js:

let cp=require(&#39;child_process&#39;);let n=cp.fork(__dirname+ &#39;./worker.js&#39;);
n.on(&#39;message&#39;,function (m) {});
n.send({hello:&#39;world&#39;});

Related recommendations:

Detailed explanation of PHP inter-process communication

The above is the detailed content of node.js fun process instance. 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