bipin
bipin

Reputation: 419

Sharing object between child and fork process node js

I'm working on child process using fork. but got totally confused on few things

• will it (process)pass app object instance eg:- let app = express(); using IPC

I m trying to explain my senario, first I have server.js where I initialize (starting point) server and other file is my task.js from where I am doing heavy task like reading a big file data and sending data back to other server. For send I had require authorization from that server whose logic is present in main.js and if any error occur I'm send email with few detail to client. Below provide code for email and authorization in main.js

 Let task = require('./task.js')
app.sendEmail = function (message, emailinfo, attachment){
 // my email logic
  }
app.auth= function(host,port)
 // Authorization logic
}
 New task(app).run()

In task.js (sample code)

Class Task { 
  constructor(app){
    this.app =app
  }
  run(){
    fs.readfile('myfile',function(err,data){

  if(err){ let msg =err; 
  let clientinf; clientinf.to = "client email"; 
  clientinf.cc = " other user in CC";
  this.app.sendEmail(msg, clientinf, attach);
  }else{
    let host='other server url';
    let port='port';
    this.app.auth(host,port);
 }
 })
  }
}

I want to run task.js in one more thread . note cluster and worker(because I m using node 10.19 so not confident that worker works properly) I don't want to use . It is possible to use folk or spawn to share data between each other. If not how I can achieve my requirement using thread?

Upvotes: 2

Views: 2283

Answers (1)

C.Gochev
C.Gochev

Reputation: 1922

Here are two solutions. The first is using the Worker class from the worker_threads module but since you don't want to update the node version the second solution is using fork function from child_process module. They do pretty much the same thing to be honest I can't tell which is better but the worker_threads solution is more recent.

Solution 1:

const { Worker } = require('worker_threads')
const task_script = path.join(__dirname, "./task.js")
 const obj = {data:"data"}
 const worker = new Worker(task_script, {
                workerData: JSON.stringify(obj)
              })
 worker.on("error", (err) => console.log(err))
 worker.on("exit", () => console.log("exit"))
 worker.on("message", (data) => {
                console.log(data)
                res.send(data)
  })

and you have to change the task.js code slightly.Here it is

const { parentPort, workerData, isMainThread } = require('worker_threads')

class Task { 
  constructor(app){
    this.app = app
  }
  run(){
if (!isMainThread) {
  console.log("workerData: ", workerData) //you have worker data here 
  fs.readfile('myfile',function(err,data){

  if(err){ let msg = err; 
  let clientinf; clientinf.to = "client email"; 
  clientinf.cc = " other user in CC";
  this.app.sendEmail(msg, clientinf, attach);
  parentPort.postMessage(msg) //use can send message to parent like this
  } else {
    let host='other server url';
    let port='port';
    this.app.auth(host,port);
     }
   })
  }
 }
}

And here is the second solution

const { fork } = require('child_process');

const forked = fork('task.js');

forked.on('message', (msg) => {
  console.log('Message from child', msg);
});

forked.send({ hello: 'world' });

and the taks.js way of sending and recieving data with this method

class Task { 
  constructor(app){
    this.app = app
  }
  run(){
  //receive
  process.on('message', (msg) => {
    console.log('Message from parent:', msg);
  });
  fs.readfile('myfile',function(err,data){

  if(err){ let msg = err; 
  let clientinf; clientinf.to = "client email"; 
  clientinf.cc = " other user in CC";
  this.app.sendEmail(msg, clientinf, attach);
   process.send(msg); //send method
  } else {
    let host='other server url';
    let port='port';
    this.app.auth(host,port);
     }
   })
  }
}

Upvotes: 2

Related Questions