【问题标题】:Node.js detach a spawned child after spawingNode.js 在生成后分离生成的孩子
【发布时间】:2013-11-04 07:57:05
【问题描述】:

我正在将 detached child_process 的 stderr 流重定向到一个文件,使用

fd = fs.openSync('./err.log', 'a');

并在spawn 中将此 fd 作为 stderr 传递。

我正在寻找一种方法来拦截写入文件的数据。这意味着,当该子进程写入某些内容时,我想在写入文件之前对其进行处理。

我尝试制作一个可写的流,并用它代替文件描述符来生成。但这没有帮助。

谁能建议我怎样才能做到这一点?

另外,我可以正常生成一个child_process (detached = false) 并监听child.stdoutdata 事件,当我准备好时,我可以分离孩子。所以基本上,我想要来自child_process 的一些初始数据,然后让它作为后台进程运行并终止父进程。

【问题讨论】:

    标签: node.js spawn child-process


    【解决方案1】:

    你想要的是Transform stream

    以下是您的问题的可能解决方案:

    var child = spawn( /* whatever options */ )
    var errFile = fs.createWriteStream('err.log', { flags: 'w' })
    var processErrors = new stream.Transform()
    processErrors._transform = function (data, encoding, done) {
      // Do what you want with the data here.
      // data is most likely a Buffer object
      // When you're done, send the data to the output of the stream:
      this.push(data)
      done() // we're done processing this chunk of data
    }
    processErrors._flush = function(done) {
      // called at the end, when no more data will be provided
      done()
    }
    
    child.stderr.pipe(processErrors).pipe(f)
    

    注意我们管道流的方式:stderr 是一个可读流,processErrors 是一个双工转换流,f 只是一个可写流。 processErrors 流将处理数据并在收到数据时将其输出(因此看起来像 PassThrough 流,内部包含您的业务内部逻辑)。

    【讨论】:

    • 这允许在写入文件之前截取数据。但是,在我从孩子那里得到一些成功确认后,我想分离那个孩子。
    • 在使用父母 stdoutstderr 之前,我无法分离孩子。基本上我不想在产卵时设置stdio: ['ignore', out, err],这样我就可以child.unref()并且父进程可以退出。
    • 在这种情况下,这很棘手,因为您甚至无法删除 processErros 流(从中取消管道 stderr 并将其重新管道传输到 f),因为 f 仍由 Node 管理,您不会能够分离它...
    • 如何创建另一个将在您的输出文件上执行tail -f 的子进程,然后将该子进程的输出传送到转换流?当你得到你想要的数据时,你可以杀死尾巴并分离你原来的孩子。哈克,但如果我正确理解您的问题,应该可以工作。
    • hmmm.. 它会解决一些问题,但仍然不是我想要的..
    猜你喜欢
    • 2016-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-30
    • 2018-09-26
    • 2011-08-11
    • 2018-02-25
    • 1970-01-01
    相关资源
    最近更新 更多