title: Forking tasks workflow in Javascript
body: <p>I'm doing some tests to learn to fork different tasks in JavaScript as I'm new to the lenguage. I'm trying to sum every thre number group from a plain text file formated as following:</p>
  <pre><code>199
  200
  208
  210
  200
  207
  </code></pre>
  <p>(199, 200, 208) is the first group, (200, 208, 210) is the second one, etc...</p>
  <p>I read from the file, splited the string and got my array of strings. Now I want to do the adding in a loop that forks every iteration (in the subprocess is where the sum is being made) and print the resulting array of summed numbers.</p>
  <p><strong>parent.js</strong></p>
  <pre class="lang-js prettyprint-override"><code>const fs = require('fs');
  const { fork } = require('child_process');
  
  const readString = fs.readFileSync('depth_readings_p2.txt', 'utf8');
  const readArray = readString.split('\n');
  
  var numArrayDef = [];
  
  for (let i = 0; i &lt; readArray.length - 2; i++) {
      let msg = {
          i,
          readArray
      };
  
      let childProcess = fork('function.js');
  
      childProcess.send(msg);
  
      childProcess.on('message', (m) =&gt; {
          console.log(m);
          numArrayDef.push(m);
      });
  
      console.log(numArrayDef[i]);
  }
  </code></pre>
  <p>As you see I'm sending the subprocess and object that includes the index, the array of strings and the array where the summed number will be stored. The parent process recieves the summed number and stores it in numArrayDef.</p>
  <p><strong>function.js</strong></p>
  <pre class="lang-js prettyprint-override"><code>process.on('message', (msg) =&gt; {
      let num = 0;
  
      if ((msg.i + 2) &lt; msg.readArray.length) {
          num += parseInt(msg.readArray[msg.i]);
          num += parseInt(msg.readArray[msg.i + 1]);
          num += parseInt(msg.readArray[msg.i + 2]);
  
          process.send(num);
      }
  
      process.exit();
  });
  </code></pre>
  <p>In the output I can see that the parent is receiving everything correctly, but the program isn't pushing the received values into the result array. Also, the order of execution is weird:
  - First, everything in the loop but the message receiving block.
  - Second, everything after the loop ends.
  - Finally, the message receiving block.</p>
  <pre><code>undefined
  undefined
  undefined
  undefined
  undefined
  undefined
  undefined
  undefined
  []
  607
  618
  618
  617
  647
  716
  769
  792
  </code></pre>
  <p>I know I'm missing something about forking processes, but I don't know what is it and I don't see it in the <a href="https://nodejs.org/api/child_process.html" rel="nofollow noreferrer">fork documentation</a>.</p>