Open5

Denoメモ

kat0hkat0h

サクッとhttp server

前提

deno: 1.14.0
deno_std: @0.108.0

serveするhtml

<!DOCTYPE html>
<html>
  <head>
  </head>
  <body>
    test
  </body>
</html>

server.ts

import { listenAndServe } from "https://deno.land/std@0.108.0/http/mod.ts";

const main = async () => {
  // fileを読み込み
  const body = await Deno.readTextFile("./index.html");

  listenAndServe(":8000", (req) => {
    if (req.url === "http://localhost:8000/") {
      return new Response(body, {
        status: 200,
        headers: new Headers({ "content-type": "text/html" }),
      });
    } else {
      return new Response("404", { status: 404 });
    }
  });
}

main()
kat0hkat0h

サクッとWebsocket(ちょい改造版)

// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.
import { serve, listenAndServe } from "https://deno.land/std@0.108.0/http/server_legacy.ts";
import {
  acceptWebSocket,
  isWebSocketCloseEvent,
  isWebSocketPingEvent,
  WebSocket,
} from "https://deno.land/std@0.108.0/ws/mod.ts";

async function handleWs(sock: WebSocket) {
  console.log("socket connected!");
  try {
    for await (const ev of sock) {
      if (typeof ev === "string") {
        // text message.
        console.log("ws:Text", ev);
        await sock.send(ev);
      } else if (ev instanceof Uint8Array) {
        // binary message.
        console.log("ws:Binary", ev);
      } else if (isWebSocketPingEvent(ev)) {
        const [, body] = ev;
        // ping.
        console.log("ws:Ping", body);
      } else if (isWebSocketCloseEvent(ev)) {
        // close.
        const { code, reason } = ev;
        console.log("ws:Close", code, reason);
      }
    }
  } catch (err) {
    console.error(`failed to receive frame: ${err}`);

    if (!sock.isClosed) {
      await sock.close(1000).catch(console.error);
    }
  }
}

if (import.meta.main) {
  /** websocket echo server */
  const port = Deno.args[0] || "8000";
  console.log(`websocket server is running on :${port}`);
  listenAndServe(`:${port}`, (req) => {
    const { conn, r: bufReader, w: bufWriter, headers } = req;
    acceptWebSocket({
      conn,
      bufReader,
      bufWriter,
      headers,
    })
      .then(handleWs)
      .catch(async (err) => {
        console.error(`failed to accept websocket: ${err}`);
        await req.respond({ status: 400 });
      });
  })
}
<!DOCTYPE html>
<html>
  <head>
    <script>
      const socket = new WebSocket('ws://localhost:8000');
      socket.addEventListener('open', function (event) {
              socket.send('Hello Server!')
            })
      socket.addEventListener('message', function (event) {
              console.log('Message from server', event.data)
            })
    </script>
  </head>
  <body>
  </body>
</html>

index.htmlを適当に開くとconnectionが確立、consoleからsocket.send('hoge')などでとりあえず接続できる

kat0hkat0h

Deno.run({ cmd: ["echo", "abcd"] })
シェルコマンドの実行