如何使spawnSync和fs.readFile一个接一个地执行? [英] How to make spawnSync and fs.readFile to execute one after other?

查看:122
本文介绍了如何使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();
    }
  });
})

这篇关于如何使spawnSync和fs.readFile一个接一个地执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆