如何使spawnSync和fs.readFile一个接一个地执行?
我有一个Python脚本,该脚本通过将FILE作为输入来返回JSON
文件作为输出.
I have a python script which returns a JSON
file as output by taking a FILE as input.
我有10个文件,我在 for循环中使用 spawnSync ,在内部循环中,我有 fs.readFile 来读取JSON文件,来自python脚本.
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.
但是问题是 spawnSync 阻止了 fs.readFile ,直到它执行所有10个文件的python脚本.由于 spawnSync 和 fs.readFile 都在 for循环中,所以我希望 fs.readFile 读取JSON文件一旦第一个python脚本执行并输出JSON文件.
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.
但是这没有发生. spawnSync 被阻止,并且正在继续执行下一个文件来执行python脚本. fs.reafFile 应该在文件执行后立即打印数据.请帮助,这是我的代码段.
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);
}
});
}
如果您依赖使用第三方模块,则建议使用 async 的方法解决此问题的模块
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();
}
});
})