0

I have a node http server.It has a main process and i have forked child process / webworker in it.

I want that the main node process handle the http request and pass this request to the forked process or web worker so that they can independently handle the request and send response to it.

Problem:- Here i am not being able to send the response object to child process/ web-worker.

Node does not allow to share variables as well. so i can not store it on the parent process and share its reference with child processes.

Is there any way by which it is possible?

1 Answers1

0

As you say, you can't pass the response object. However, you can pass some sort of identifier that lets the main thread retrieve the correct response object when the worker has done its work.

For example you can

  • In the main thread, store each response object by a unique integer ID
  • Pass this ID to the worker
  • When the worker is done, pass this ID back to the main thread along with the results of its work
  • The main thread retrieves the correct response object, and passes the result back to the client (i.e. the web browser)

Below is a basic implementation

var http = require('http');
var Worker = require('webworker-threads').Worker;

// Store in-progress responses by unique(-enough) ID
// that is passed to the worker that then passes it back
var responses = {
  _nextResponseId: 0,
  _responses: {},
  store: function store(response) {
    var id = this._nextResponseId;
    this._nextResponseId = this._nextResponseId === Number.MAX_SAFE_INTEGER ? 0 : (this._nextResponseId + 1);
    this._responses[id] = response;
    return id;
  },
  remove: function remove(id) {
    var response = this._responses[id];
    delete this._responses[id];
    return response;
  }
};

// Worker,simulating something long and synchronous
var worker = new Worker(function() {
  onmessage = function(event) {
    var id = event.data.id;
    for (var i = 0; i < 1000000000; ++i) {}
    self.postMessage({
      id: id,
      message: 'From worker, request ' + id
    });
  };
});

// A worker message ends the original http response
worker.onmessage = function(event) {
  var response = responses.remove(event.data.id);
  response.end(event.data.message);
};

// Simple server that calls the worker with the id of the response
var server = http.createServer(function handleRequest(request, response) {
  var id = responses.store(response);
  worker.postMessage({
    id: id
  });
});
server.listen(8083);
Michal Charemza
  • 25,940
  • 14
  • 98
  • 165