如何从childProcess.stderr.on('data')停止子进程

时间:2018-10-02 11:07:37

标签: node.js kill child-process spawn

我的stderr内部发生错误,但是没有被触发,并且进程退出,代码为0。 因此,我分析了我的stderr并尝试在此函数内停止子进程。 这是我的代码:

    exports.runCmd = function (req, res, cmd, originalFile, newFile) {
  const promise = spawn(cmd, { shell: true })
  const childProcess = promise.childProcess

  console.log(cmd)

  childProcess.stderr.on('data', function (data) {
    console.error("STDERR:", data.toString())
    if (data.toString() === 'Can not open the file as archive' || data.includes('Document is empty')) {
      childProcess.kill()
      genericFunctions.resError(res, 415, 'Type de fichier non supporté 3')
    }
  })
  childProcess.stdout.on('data', function (data) {
    //console.log("STDOUT:", data.toString())
  })
  childProcess.on('error', function (err) {
    genericFunctions.resError(res, 415, 'Type de fichier non supporté 4', err)
  })
  childProcess.on('exit', function (exitCode) {
    console.log("Child exited with code: " + exitCode)

    if (res === undefined) {
      fs.unlinkSync(originalFile)
      return true
    } else if (!fs.existsSync(newFile)) {
      console.log('Le fichier n\'existe pas')
      genericFunctions.resError(res, 415, 'Type de fichier non supporté 5')
    } else if (typeof req.body.download !== 'undefined' && req.body.download) {
      console.log('Téléchargement')
      genericFunctions.resDownload(req, res, originalFile, newFile)
    } else {
      console.log('Envoi du lien')
      genericFunctions.resLink(req, res, originalFile, newFile)
    }
  })
}

所以我尝试停止childProcess.kill(),但是我仍然从stderr获得另一行,因此它重新设置了标头和应用程序崩溃

0 个答案:

没有答案