【问题标题】:NodeJS read partial streamNodeJS 读取部分流
【发布时间】:2020-12-24 21:17:57
【问题描述】:

我有一个 NodeJS 子进程,它在调用时会计算一个唯一的 pid(由 redis 使用)

我和控制台记录它(例如:console.log('PID: ' + pid)

在父母中我打电话给spawn(command, arg, {stdio: ['pipe', 'pipe', 'pipe'], detached: true})

我尝试过的一些事情:

  1. 关闭子进程 stdout 并将其传递给一个函数(返回一个承诺),然后
return new Promise((resolve, reject) => {
    inputStream.on('data', (i) => {
      const isPidString = RegExp('/^PID:.+/g').test(i.toString('utf8'))
      console.log('isPidString', isPidString)
      if (isPidString) {
        console.log('found string')
        console.log('i', i.toString())
        const pidValue = parseInt(i.toString('utf8').split(': ')[1])
        console.log('pidVal', pidValue)
        inputStream.destroy()
        resolve(pidValue)
      }
    })
    
    setTimeout(() => {
      reject()
    }, 5000);
  });

不知何故,它不起作用。我的问题是:我如何只为我关心的一个特定的 console.log() 收听一个流(那将不间断地运行)。

【问题讨论】:

    标签: node.js child-process node-streams


    【解决方案1】:

    编辑:能够解决这个问题 该代码大部分工作,这是所需的:

    1. 克隆子进程标准输出(我们要从中读取数据)
    2. 读取字符串(使用utf-8编码转换成字符串)
    3. 当输出与正则表达式字符串匹配时,您可以使用字符串操纵器来提取值、销毁流并解析。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-02
      • 1970-01-01
      • 2017-05-11
      • 2021-06-03
      相关资源
      最近更新 更多