child_process流背压

时间:2016-01-24 23:37:19

标签: node.js stream stdio

我正在使用带有Node.js的exec-stream和流经其他一些转换流的管道,最终通过node-brake流来限制数据速率。制动流似乎没有效果,实际上数据最终会在长链末端丢失。

execStream('some-external-binary').pipe(transform1).pipe(transform2).pipe(brake(1024))

我认为发生的事情是child_process STDOUT流(exec-stream内)没有暂停,因此填充缓冲区直到数据丢失。

child_process个流的行为是这样的吗?有没有办法让背压与child_process流一起正常工作?

1 个答案:

答案 0 :(得分:1)

我对exec-stream和node-brake不太熟悉,无法理解数据丢失的所有途径。

然而,我做了一个小实验,看看节点制动是否有背压效应,你提到它可能是数据丢失的潜在区域。

文件也托管在Gist

###
Created for http://stackoverflow.com/questions/34982953/child-process-stream-backpressure
Please pardon the CoffeeScript, but I couldn't stand to extend stream.Transform in native JavaScript.
###
fs = require("fs")
execStream = require("exec-stream")
brake = require("brake")

file = fs.createWriteStream("tmp.txt")

class Double extends require("stream").Transform
  _transform: (chunk, enc, cb) ->
    @_last ?= Date.now()
    @_called ?= []
    @_called.push Date.now() - @_last
    @_last = Date.now()
    @push chunk.toString() + chunk.toString()
    cb()

class UpperCase extends require("stream").Transform
  _transform: (chunk, enc, cb) ->
    @push chunk.toString().toUpperCase()
    cb()

sum = (nums) ->
  o = 0
  o += i for i in nums
  o

doTest = (size) ->

  transform1 = new Double()
  transform2 = new UpperCase()
  transform3 = new Double()

  execStream("dd", ["if=/dev/urandom", "bs=1024", "count=1"])
    .pipe(transform1)
    .pipe(transform2)
    .pipe(brake(size))
    .pipe(transform3)
    .pipe(file)

  file.on "finish", ->
    fs.stat "tmp.txt", (err, stats) ->
      throw err if err
      called1 = transform1._called
      averagePreBrake = sum(called1) / called1.length
      called2 = transform3._called
      averagePostBrake = sum(called2) / called2.length
      console.log """
        Generated with brake(#{size}): #{stats.size}
        Average time between transformations pre-brake:  #{averagePreBrake}ms
        Average time between transformations post-brake: #{averagePostBrake}ms
      """

doTest 1024
doTest 256

该过程的结果如下。

stdout from above Coffeescript

我注意到制动前的转换之间没有间隙。但是,制动器会破坏后续的变换。鉴于这些数据,我怀疑节点制动没有背压效应。

[我的sh2png实用程序生成的控制台输出的屏幕截图]