Deno nuggets: Convert bytes to readable stream

Mayank C
Tech Tonic

--

This article is a part of the Deno nuggets series, where each article attempts to suggest a pointed solution to a specific question that can be read in less than a minute. There is no ordering of nuggets.

Problem

How to convert arbitrary bytes to readable stream?

Solution

At times, there is a need to convert arbitrary bytes to readable stream that be either sent in request to an HTTP server, response from an HTTP server, redirected to a file, etc.

The easiest way to convert bytes to readable stream is using web standard Blob API. The Blob constructor takes any number of typed arrays as input. The Blob object concatenates the input arrays. Additionally, the Blob object also provides a stream API to convert the Blob contents to a readable stream.

Here is an example of a response from an HTTP server (blob can be used directly in response body too):

import { serve } from "https://deno.land/std/http/mod.ts";
const data1 = new Uint8Array([72, 101, 108, 108, 111, 32, 102, 114, 111, 109]),
data2 = new Uint8Array([32, 68, 101, 110, 111]);
const data = new Blob([data1, data2]);
serve(() => new Response(data.stream()));

Here is a test:

> curl http://localhost:8000
Hello from Deno

Here is an example of writing to a file using blob as stream:

const data1 = new Uint8Array([72, 101, 108, 108, 111, 32, 102, 114, 111, 109]),
data2 = new Uint8Array([32, 68, 101, 110, 111]);
const data = new Blob([data1, data2]);
data.stream().pipeTo(
(await Deno.open("./some-file.txt", { create: true, write: true })).writable,
);

--

--