deno - how to serve images

Viewed 855

I want to serve an image in deno. I'm using the following code (simplified to be easier to read). If I try it on a textfile and set the contenttype to text/plain it works perfectly fine. If I try it with an image, it does send the content of the file but for some reason the browser tells me the file contains errors. Any Idea why that is? (I'm completely new to deno so it might be something really obvious.)

import { serve } from "https://deno.land/std/http/server.ts";
import { readFileStr } from 'https://deno.land/std/fs/read_file_str.ts';

for await (const req of serve({ port: 80 })) {
    const img = await readFileStr('./myfolder/cat.png');

    const head = new Headers();
    head.set('content-type', 'image/png');

    req.respond({ headers: head, body: img, status: 200 });
}
1 Answers

You're using readFileStr which should only be used for text files, since the content is converted to a UTF-8 string. For working with binary files, such as images, you need to use Deno.readFile

for await (const req of serve({ port: 80 })) {
    const img = await Deno.readFile('./myfolder/cat.png');

    const head = new Headers();
    head.set('content-type', 'image/png');

    req.respond({ headers: head, body: img, status: 200 });
}

Deno.readFile works for text files too.

Related