【问题标题】:How to read data from nodejs spawn as it is received如何从接收到的nodejs spawn读取数据
【发布时间】:2018-11-03 01:30:19
【问题描述】:

我有一个 nodejs 程序的小问题。我正在尝试使用 child_process 模块,但以下代码只会在我从 nfc 读卡器中取出卡后触发 data 事件。

问题是我需要的输出在卡被移除之前就已经可用了。

例如,如果我将卡放在读卡器上,则需要半秒钟才能打印出一些包含卡 UID 的行。

如果我不释放卡,程序nfc-poll 仍然可以工作,但不会输出任何内容。一旦我从读卡器中取出我的卡,它就会输出一些东西,然后关闭缓冲区。这是发出事件data 的时间。

我想要的是能够尽快读取每个字节以尽快发出卡 ID。

function NFCReader() {
  this.reader = new events.EventEmitter()
  this.start_process()
}

NFCReader.prototype = {
  start_process: function () {
    this._process = cp.spawn('nfc-poll', [], {})
    this._process.on('close', this.restart_process.bind(this))
    //this._process.stdout.on('data', this.handle_data.bind(this))
    this._process.stdout.readableFlowing = true
    this._process.stdout.on('data', this.handle_data.bind(this))
    this._process.stderr.on('data', this.handle_error.bind(this))
  },

  handle_data: function (data) {
    var _data = data.toString()
    var uid_lines = _data
      .split('\n')
      .filter(function (line) {return line.search('UID') >= 0})

    if (uid_lines.length != 1) {
      this.reader.emit('error', 'Multiple UID found')
      return
    }

    var card_id = uid_lines[0]
      .trim()
      .split(':')[1].trim()
      .replace(/[ ]+/g, ':')

    this.reader.emit('card', card_id)
  },
}

我尝试使用管道,但似乎没有帮助。

【问题讨论】:

    标签: node.js stream child-process


    【解决方案1】:

    这是来自我的release tools repo 的 runStream 函数:

    const stdin = input ? "pipe" : "ignore";
    const out = new StringStream();
    const child = execspawn(cmd, Object.assign(options, {
        stdio: [stdin, "pipe", 2]
    }));
    
    child.on("error", e => out.emit("error", e));
    
    if (input) {
        input.pipe(child.stdin);
    }
    return child.stdout.pipe(out);
    

    您可以复制它,或者如果您愿意等待几天,我可以将它作为一个单独的模块发布。我想可能已经有类似的东西了......

    【讨论】:

    • 从我读到的内容不会有任何帮助,因为我正在运行的程序不会刷新其缓存,因此 nodejs 应用程序仅在进程退出时才从标准输入接收数据,因为数量数据太小而无法溢出管道缓存。我能想到的唯一解决方法是减少缓存大小或更改我正在运行的应用程序。
    • 好吧 - 如果看起来是这样的话......我会尝试调整 stdbuf 参数......这可能会影响管道的系统处理。
    猜你喜欢
    • 2020-11-23
    • 2023-04-09
    • 1970-01-01
    • 2017-08-22
    • 2022-11-29
    • 2013-05-25
    • 1970-01-01
    • 2019-01-07
    • 1970-01-01
    相关资源
    最近更新 更多