How do I post a file to Server using Deno fetch API / or convert a file to a RedableStream?

Viewed 740

How do I convert a file to Readable stream ? I am trying to use deno's fetch api to do this, which requires a readable stream as body to put something on server. I am not able to figure out how to convert a file to ReadableStream ?

1 Answers

There isn't a built-in way yet to convert a Reader to a ReadableStream.

You can convert it using the following code:

const file = await Deno.open("./some-file.txt", { read: true });

const stream = new ReadableStream({
  async pull(controller) {
    try {
      const b = new Uint8Array(1024 * 32);
      const result = await file.read(b);
      if (result === null) {
        controller.close();
        return file.close();
      }

      controller.enqueue(b.subarray(0, result));
    } catch (e) {
      controller.error(e);
      controller.close();
      file.close();
    }
  },
  cancel() {
    // When reader.cancel() is called
    file.close();
  },
});

// ReadableStream implements asyncIterator
for await (const chunk of stream) {
  console.log(chunk);
}

Have in mind that Deno (1.0.5) fetch does not yet support a ReadableStream as request body.

So currently to post a file, you'll need to buffer the contents.

const body = await Deno.readAll(file);
await fetch('http://example.com', { method: 'POST', body });
Related