naik3 naik3 - 2 months ago 13
JSON Question

How to make spawnSync and fs.readFile to execute one after other?

I have a python script which returns a

JSON
file as output by taking a FILE as input.

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

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

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

var spawn = require('child_process').spawnSync;
var fs = require('fs');
var filename = ['first.txt','second.txt','third.txt',....]
for(var i=0;i<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);
}
});
}

Answer

If you are rely to use third party module then I recommend to use async.eachSeries the method of the async module to resolve this issue

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();
    }
  });
})
Comments