Deno nuggets: Convert file to 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 stream a local file via HTTP?

> curl http://localhost:5000/testdata/sample2.txt
Deno
is
Awesome!

Solution

Imports

A function named readableStreamFromReader needs to be imported from standard library’s io module. This function is useful in converting a Deno.Reader to ReadableStream.

import {readableStreamFromReader as toStream} from "https://deno.land/std/io/mod.ts";

File to stream

There are two steps in converting a file to stream:

  • Open file to get a Deno.Reader object
  • Convert Deno.Reader to ReadableStream using readableStreamFromReader function
import {readableStreamFromReader as toStream} from "https://deno.land/std/io/mod.ts";toStream(await Deno.open('./someFile.txt'));

Complete code

Here is the complete code of an HTTP server that serves file paths relative to current directory as specified in the URL path (like http://localhost:5000/dir1/dir2/file1.txt):

import { readableStreamFromReader as toStream } from "https://deno.land/std/io/mod.ts";
import { exists } from "https://deno.land/std/fs/mod.ts";
import { serve } from "https://deno.land/std/http/mod.ts";
async function reqHandler(req: Request) {
const filePath='./'+(new URL(req.url)).pathname;
if(await exists(filePath))
return new Response(toStream(await Deno.open(filePath)));
else
return new Response(null, { status: 404 });
}
serve(reqHandler, { port: 8000 });

Here is the output of a sample run:

> cat ./testdata/sample2.txt
Deno
is
Awesome!
> curl http://localhost:5000/testdata/sample2.txt
Deno
is
Awesome!
> curl http://localhost:5000/testdata/someFile.txt
HTTP/1.1 404 Not Found

--

--