How to get notified when data is actually ready for streaming?

137 Views Asked by At

I have two streams:

  • a source stream, which downloads an audio file from the Internet
  • a consumer stream, which streams the file to a streaming server

Before streaming to the server there should be a handshake which returns a handle. Then I have a few seconds to really start streaming or the server closes the connection.

Which means, that I should

  • FIRST wait until the source data is ready to be streamed
  • and only THEN start streaming.

The problem is that there doesn't seem to be a way to get notified when data is ready in the source stream.

The first event that comes to mind is the 'data' event. But it also consumes the data which is not acceptable and doesn't allow to use pipes at all.

So how to do something like this:

  await pEvent(sourceStream, 'dataIsReady');
  // Negotiate with the server about the transmission
  sourceStream.pipe(consumerStream);

Thanks in advance.

1

There are 1 best solutions below

0
On

Answering to myself.

Here is a solution which works for me.

It requires an auxiliary passthrough stream with a custom event:

class DataWaitPassThroughStream extends Transform {
  dataIsReady: boolean = false;

  constructor(opts: TransformOptions) {
    super(opts);
  }

  _transform(chunk: any, encoding: BufferEncoding, callback: TransformCallback) {
    if (!this.dataIsReady) {
      this.dataIsReady = true;
      this.emit('dataIsReady');
    }
    callback(null, chunk);
  }
}

Usage

import pEvent from 'p-event';

const dataReadyStream = sourceStream.pipe(new DataWaitPassThroughStream());
await pEvent(dataReadyStream, 'dataIsReady');

// Negotiate with the server about the transmission...

dataReadyStream.pipe(consumerStream);