How to do multithreading in node js child process

こ雲淡風輕ζ 提交于 2020-01-06 11:49:33

问题


I have a bash script that called for multiple times with unique id and I have used socket io to send messages on stdout function

The shell script contains two actions:

  1. Action1
  2. Action2

Action2 is a background process so I don't want to wait for the script completion so when the Action1 got completed then I print echo message (msg) which I will capture in the stdout function and then I sent the socket io message inside the stdout function

server.js

child_process = exec('bash some-file.sh arg1 arg2')

child_process.stdout.on('data', function) {
  if ((data).indexOf(msg) > 1) {
    io.sockets.emit('Completed for id: ' + id)
  }
});

The problem with the above code is when I call the above action multiple times it doesn't work for second iteration (i.e id 1 still there) since the background action (Action2) is still running in the background for id 1.

How to do multithreading on child_process?


回答1:


you can use child_process.fork and send the message from your subprocess (Actions2)

main.js

const child_proc = require('child_process');
const sub = child_proc.fork(`${__dirname}/sub.js`);
sub.on('message', (m) => {
  console.log('PARENT got message:', m);
});
sub.send({ from: 'server' });

sub.js

process.on('message', (m) => {
  console.log('CHILD got message:', m);
});
process.send({ from: 'client' });

Here are the document and a good article explained it



来源:https://stackoverflow.com/questions/52057838/how-to-do-multithreading-in-node-js-child-process

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!