LoginSignup
2
2

More than 3 years have passed since last update.

Deno+HTMLでHello World

Posted at

概要

denoを使用してHTMLファイルを読み込んで、
Hello Worldをブラウザ上で表示させます。
Deno

環境

Mac
Deno v1.0

インストール

Homebrewを使用してインストールします。

$ brew install deno

正しくインストールされたか確認します。

$ deno -V

サーバーを立てる

ローカルにサーバーを立てていきます。

server.ts
import { serve } from "https://deno.land/std@0.53.0/http/server.ts";

const s = serve({ port: 8000 });

for await (const req of s) {
  req.respond({ body: "Hello World\n" });
}

コマンドで実行します。

$ deno run --allow-net server.ts 

※Denoデフォルトでセキュアであり、明示的に有効にしない限り、ファイル、ネットワーク、環境変数等にアクセスすることができません。

今回ネットワークを許可するために、--allow-netフラグを付与して実行しました。

動作確認

以下にアクセスしてHello Worldと表示されればOKです。
http://localhost:8000/

HTMLを読み込んで表示

HTMLファイルを用意します。

index.html
<!DOCTYPE html>
<html lang="ja">
    <head>
        <meta charset="UTF-8">
    </head>
    <body>
        <p>Hello World</p>
    </body>
</html>

HTMLを読み込むための準備

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

fsモジュールのreadFileStrを使用してHTMLファイルを読み込みます。

 
readFileStrでHTMLを読み込んで返します。

server.ts
async function getHtml(): Promise<any> {
  const html = await readFileStr('./public/index.html');

  return { html }
}

 

最終的に以下のようになるかと思います。

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

const s = serve({ port: 8000 });

async function getHtml(): Promise<any> {
  const html = await readFileStr('./public/index.html');

  return { html }
}

for await (const req of s) {
  req.respond(await getHtml());
}

以下のコマンドを実行します。

$ deno run --allow-net --allow-read  server.ts 

ファイル読み込みを許可するために、--allow-readフラグを付与して実行しました。

動作確認

以下にアクセスしてHello Worldと表示されればOKです。
http://localhost:8000/

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2