How to split incoming json stream into individual json messages in NodeJS

453 Views Asked by At

I am looking for a solution which could be piped to my existing streams so that this input:

{ "foo":"bar" }{ "foo": { "foo": "bar" }}

Would display this:

{ "foo":"bar" }
{ "foo": { "foo": "bar" }}

Using this code:

incomingStream.pipe(jsonSplitter()).on('data', (singleJson) => {
    console.log(singleJson)
});

Any packages?

1

There are 1 best solutions below

0
On BEST ANSWER

Ok so you can use stream-json npm package. In order to achieve what I asked in the question you would need this code:

import { parser } from 'stream-json';
import { streamObject } from 'stream-json/streamers/StreamObject';

...

stream
  .pipe(parser({ jsonStreaming: true }))
  .pipe(streamObject())
  .on('data', (data: any) => {
    console.log(data);
  });