异步创建NodeJS子进程

时间:2017-08-05 09:31:49

标签: node.js asynchronous child-process

我在一个名为" pythonGraphTools"的函数中在NodeJS中创建子进程。在生成一些需要传入的变量之后的for循环中。这个for循环可以运行50次。

然后我写信给衍生过程的标准输入。但是,有时我会得到一个"错误:EPIPE写入已关闭的套接字"此行py.stdin.write(JSON.stringify(dotfilepath));

的错误

我怀疑这是因为子进程还没有完成产生,并且在没有准备好的时候尝试写入它。我在https://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options上看到了异步生成,但是这些似乎只有从子节点到父节点的数据/消息流的异步事件。

在调用py.stdin.write()

之前,我如何确保孩子完全生成的任何见解
 function pythonGraphTools(dotfilepath,allGraphsPerTrans,graphtools_color,graphtools_label,transHashArray){
  var spawn = require('child_process').spawn,
      py    = spawn('python', ['python_module.py']);
  //write file to disk temporarily.
  console.log("dotfilepath is "+dotfilepath)
  fs.writeFile(dotfilepath,allGraphsPerTrans, function(err){ //must create a file first //2nd param was res_str_dot_no_lbl
    if(err){
      console.log("there was an error writing to file" + err);
    }
    //now send this dot file path to the python module which will make the graph
    console.log("now writing to python module!"+py.pid)
    console.log("nodejs colorarray length for debuging "+ graphtools_color.length)
    py.stdin.write(JSON.stringify(dotfilepath)); //sending data to the python process!
    py.stdin.write("\n")
    py.stdin.write(JSON.stringify(graphtools_color)); // sending colours
    py.stdin.write("\n")
    py.stdin.write(JSON.stringify(graphtools_label));//sending opcodes
    py.stdin.write("\n");
    py.stdin.write(JSON.stringify(transHashArray));//sending opcodes
    py.stdin.write("\n");
    py.stdin.end();
  });
  var dataString=""; //variable to store return from python module
  py.stdout.on('data', function(data){ // listen for data coming back from python!
    dataString += data.toString();
  });

  py.stdout.on('end', function(){ //pythons stdout has finished - now do stuff
    console.log(dataString); // print out everything collected from python stdout
    //now delete temp dot file (with all dot files in it)
    fs.stat(dotfilepath, function (err, stats) { //check first if there is a dot file
      console.log(stats);//here we got all information of file in stats variable
      if (err) {
          return console.error(err);
      }
      fs.unlink(dotfilepath,function(err){ //actually deleting comment this functiont to not delete
           if(err) return console.log(err);
           console.log('file deleted successfully');
      });//end unlink
    });//end file stat
    py.stdout.end();
  }); // on python 'finish'

  py.on('exit', function (code, signal) { //which process? add pid ?

  console.log('child process '+py.pid +' exited with ' +
              `code ${code} and signal ${signal}`);
  });
}

0 个答案:

没有答案