Search code examples
javascriptstreamprotocol-buffers

transform a byte array to a readablestream


Hi I am stuck on this issue,

I reconstructed a few protobuf object in order to seed data to my miragejs instance,

  const unknownObject = new core.UnknownObject()
  const unknownEntity = new message.UnknownObjectEntity()
  const unknownEntityRepo = new message.UnknownObjectEntityRepository()
  const unknownObjectNotification = new message.UnknownObjectNotification()

  const date = new google_protobuf_timestamp_pb.Timestamp()

  unknownObject.setImage(Base64())
  unknownObject.setTimestamp(date)
  unknownObject.setWaypoint(new core.Waypoint())

  console.log('unknownObject:', unknownObject.getTimestamp())

  unknownEntity.setId('1')
  unknownEntity.setUnknownobject(unknownObject)

  console.log('unknownEntity:', unknownEntity)

  const endBuffer = unknownEntityRepo.addEntity(unknownEntity).serializeBinary()

the end result (endBuffer) is a byte array. I want to reconstruct this byte array into a readablestream in order to seed the data. This is the final result needed.

ReadableStream {locked: false}

I can only fund resources made to be used to read the stream but never the transform a byte array into the ReadableStream.

Does anyone have experience with this. Thanks


Solution

  • You need to implement ReadableStream and add your content to the controller. Mozilla's MDN Web Docs provide some guidance in their simple random string example.

    Here is a simplified example:

    function buildStream(data)
    {
        //depending on what data is and how it will be used, you may need to convert it
        //data = Uint8Array.from(data);
        
        return new ReadableStream({
            start(controller) {
                // Add the data to the stream
                controller.enqueue(data);
            },
            pull(controller) {
                // nothing left to pull, so close
                controller.close();
            },
            cancel() {
                //nothing to do
            }
        });
    }