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);