Node.js child process fork return response — Cannot set headers after they are sent to the client

copied from stack overflow since no one could answer.

situation: have an function that does an expensive operation such as fetching a large query from mongodb, then performing a lot of parsing and analysis on the response. I have offloaded this expensive operation to a child process fork, and waiting for the worker to be done before sending response in order to not block the main event loop.

current implentation: I have an API endpoint GET {{backend}}/api/missionHistory/flightSummary?days=90&token={{token}}

api entry point code:


const cp = require('child_process'); //if reportChild is initailzed here, "Cant send headers after they were sent" const reportChild = cp.fork('workers/reportWorker.js');   exports.flightSummary = function (req, res) {     let request = req.query;      // if initialized here, there is no error.      const reportChild = cp.fork('workers/reportWorker.js');      logger.debug(search_query);      let payload = {'task':'flight_summary', 'search_params': search_query};     reportChild.send(payload);      reportChild.on('message', function (msg) {;         if (msg.worker_status === 'completed')        {            return res.json(;        }       }); }; 

worker code: reportWorker.js

process.on('message', function (msg) {     process.send({'worker_status': 'started'});     console.log(msg);     switch(msg.task)     {         case 'flight_summary':             findFlightHours(msg.search_params,function (response) {       'completed')                 process.send({'worker_status': 'completed', 'data':response});             })         break;     }   }); 

scenario 1: reportChild (fork) is initialized at beginning of module definitions. api call works once, and returns correct data. on second call, it crashes with cannot send headers after theyve been sent. I stepped through the code, and it definitely only sends it once per api call.

scenario 2: if i initalize the reportChild inside of the api definition, it works perfectly every time. Why is that? Is the child forked process not killed unless its redefined? Is this standard implementation of child proceses?

This is my first attempt at threading in node.js, I am trying to move expensive operations off of the main event loop into different workers. Let me know what is best practice for this situation. Thanks.