从子进程标准输出中连续读取 json

continuously read json from childprocess stdout

我想在 nodejs 中从 java 子进程读取和发送 json 消息。子进程将存在一段时间。通过 stdio 发送和接收的消息表示来自和向两个进程发送的事件。因此,消息必须在完成后立即处理。

输出格式为

{"type":"eventType","data":...}
{"type":"anotherEventType","data":...}
...
{"type":"anotherEventType","data":...}

写消息没问题,但阅读是。特别是因为我不能依赖 \n 上的消息拆分,也不能依赖一个块只包含一条消息。

不幸的是,我能找到的每个示例都会缓冲 stdout 的输出,直到进程终止,然后才解析它。我能找到的所有 IPC 节点模块都使用我想避免的套接字。

是否有提供此类功能的现有库,还是我必须自己扮演角色?

JSONStream 完全符合我的要求。

child.stdout
    .pipe(require('JSONStream').parse())
    .on('data', processMessage);