How to consume Event-stream with nodejs

Asked

Viewed 101 times

2

I have a nodejs application that needs to consume an endpoint that returns a text/event-stream. The application that issues these events is done with java and packages a data within an object ServerSentEvent containing id, Event, Retry, comment and date, where data is my message. To consume endpoint I tried to use some lib from eventSource but none worked as expected. Now I’m trying to consume using the lib http, thus:

http.get({
    agent: false
    , path: "/streaming"
    , hostname: "localhost"
    , port: 8080
}, (res) => {
    res.on('data', data => {
        console.log(data);
    })
});

Observing the object data that is returned, I notice that it is of the type Buffer. However I can not convert it to a format that I can manipulate. What should be the right way to consume this endpoint? Keep searching for a lib of EventSource or there is a way to consume using lib http?

PS: The Node application does not load anything in the browser, it is just backend. Node V10.16.3

Edited

An example project containing the possible test media can be seen here: https://github.com/josecarlosweb/sse-emit-test

  • Can you provide a minimum verifiable example? Because if the ones you tested didn’t work it must be due to some particularity of your API

  • Great idea @Sorack. Creating here now.

  • I added an example project

  • 1

    If it is a stream, the information does not arrive all at once, you need to gradually consume the buffer. How to do this depends on the library you’re using on the client side, but I imagine that everyone who supports streams offers a way to deal with it.

1 answer

3


Like bfavaretto quoted, you need to consume little by little to form the complete answer. Just use the events:

// ...
const partes = [];
res.on('data', (parte) => partes.push(parte));
res.on('end', () => console.log(Buffer.concat(partes).toString('utf8')));
// ...

Stream - Event: data

The 'data' Event is Emitted Whenever the stream is relinquishing Ownership of a Chunk of data to a Consumer.

In translation

The event 'data' shall be issued whenever the stream is assigning ownership of a piece of data to a consumer.


Stream - Event: 'end'

The 'end' Event is Emitted when there is no more data to be Consumed from the stream.

In free translation:

The event 'end' is issued when no more data is consumed from stream.


Buffer.concat

Returns a new Buffer which is the result of concatenating all the Buffer instances in the list Together.

In free translation:

Returns a new Buffer which is the result of merging all instances of Buffer together on the list.


buf.toString

Decodes buf to string According to the specified Character encoding in encoding.

In free translation:

Decodes buf for a string according to the specific table in encoding.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.