quentino
quentino

Reputation: 1201

How to recognize from which stream, the event was emitted in node.js

I have stream from Db and I'm spitting it to many HTTP servers via HTTP (request). To split this stream I use passThrough Everything works well, but when the event is called I don't know which stream emit it. Is any solution to identify that stream?. I'm using error, end, data, and response events. In response I have information about host but most important is to identify it in error eventListener.

const stream = await getDataStream(id);
const passThrough = new PassThrough();
stream.pipe(objectToString).pipe(passThrough);

for (let host of hostsList) {
  startedRequestsCount++;
  host.stream
    .on('error', errorHandler)
    .on('data', dataHandler)
    .on('response', responseHandler)
    .on('end', resolveAfterAllRequests);
  passThrough.pipe(host.stream);
}

I have a lot of doubts about this solution but for now, it's working. Problem is when I receive an error and want to know which host was failed.

Bonus question:

If I'm streaming via HTTP can I handle back pressure issue?

Upvotes: 0

Views: 48

Answers (1)

Jonas Wilms
Jonas Wilms

Reputation: 138267

When defining the handlers use currying to take an additional stream parameter:

  const errorHandler = stream => error => {
   console.log(stream, error);
 };

Then cook the curry:

 host.stream
  .on('error', errorHandler(host.stream));

for sure you can pass in multiple arguments with that pattern.

Upvotes: 1

Related Questions