How to make spawnSync and fs.readFile to execute one after other?
<p>I have a python script which returns a <code>JSON</code> file as output by taking a FILE as input.</p>

<p>I have 10 files, I am using <strong>spawnSync</strong> inside <strong>for loop</strong> and inside loop I have <strong>fs.readFile</strong> for reading JSON file which is coming from the python script. </p>

<p>But the problem is <strong>spawnSync</strong> is blocking <strong>fs.readFile</strong> until it executes python scripts with all 10 files. Since both <strong>spawnSync</strong> and <strong>fs.readFile</strong> are inside <strong>for loop</strong>, I want <strong>fs.readFile</strong> to read a JSON file as soon as first python script executes and outputs JSON file.</p>

<p>But it is not happening. <strong>spawnSync</strong> is blocking and it is continuing with next file to execute python script.<strong>fs.reafFile</strong> should prints data as soon as the file gets executes. please help, Here is my code snippet. </p>

<pre><code>var spawn = require('child_process').spawnSync;
var fs = require('fs');
var filename = ['first.txt','second.txt','third.txt',....]
for(var i=0;i&lt;10;i++)
{
  var myscript = spawn('python',['/pathToPython/myPython.py',filename[i]]);
  fs.readFile('/pathToPython/' + filename[i] + '.json','utf8',function(err,data){
         if(err){
               console.log(err);
         }else{
               console.log(data);
       }
   });
}
</code></pre>

<p>If you are rely to use third party module then I recommend to use <a href="http://caolan.github.io/async/docs.html#.eachSeries" rel="nofollow">async.eachSeries</a> the method of the <a href="https://github.com/caolan/async" rel="nofollow">async</a> module to resolve this issue</p>

<pre><code>var filename = ['first.txt','second.txt','third.txt',....]
async.eachSeries(filename, function(item, next) {

  var myscript = spawn('python', ['/pathToPython/myPython.py', item]);
  fs.readFile('/pathToPython/' + item + '.json', 'utf8', function(err, data) {
    if (err) {
      console.log(err);
    } else {
      console.log(data);
      next();
    }
  });
})
</code></pre>

javascript python json node.js express