LoginSignup
9

More than 3 years have passed since last update.

Deno: インストール〜Webサーバ起動

Last updated at Posted at 2018-12-31

Denoはまだ開発中で1.0になっていません。そのため、この記事の内容は将来的に変更されるかもしれませんのでご注意ください。
2020-05-14
Deno 1.0 がリリースされました :tada:
https://deno.land/v1

この記事はmacOS Catalina で試した内容です。

Denoとは

Node.jsのoriginal authorであるRyan Dahl氏が開発しているTypeScriptをV8で動かすラインタイム実行環境です。
DenoはNode.jsの反省点を活かして開発しています。
Ryan Dahl氏が JSConf EU 2018 でそのことについて話している動画がYouTubeにあるので興味がある方はぜひ御覧ください。

Node.jsに関する10の反省点 Ryan Dahl - JSConf EU 2018

また日本語で書かれた記事は以下の記事が詳しいです。

Node.js における設計ミス By Ryan Dahl - from scratch

インストール

インストール方法は公式の The Deno Manual にも記載されています。

shellでは以下のコマンドを実行

curl -fsSL https://deno.land/x/install/install.sh | sh

power shellでは

iwr https://deno.land/x/install/install.ps1 -useb | iex

macOSの方は Homebrew を使ってインストールすることもできます。

brew install deno

この時点でdenoコマンドが使えるようになっているので、試しに https://deno.land にあるサンプルを実行してみます。

$ deno run https://deno.land/std/examples/welcome.ts
Welcome to Deno 🦕

Hello, World

試しにHello, Worldを表示するプログラムをTypeScriptで書いて実行してみます。

hello.ts
console.log('Hello, World');
$ deno run hello.ts
Hello, World

Webサーバを起動する

localhost:8080 で起動する http サーバーを作ってみます。

hello_http.ts
import { serve } from "https://deno.land/std@0.50.0/http/server.ts";
const s = serve({ port: 8080 });
console.log("http://localhost:8080/");
for await (const req of s) {
  req.respond({ body: "<h1>Hello World</h1>\n" });
}

httpというdeno標準ライブラリを使います。
Deno は Top-level await をサポートしているので上記のように for-await-of 構文を使ってリクエストを捌くことができます。serve 関数は async iterable なクラス Server のインスタンスを返却しています。https://github.com/denoland/deno/blob/55d2c6bd103879263c115fa5697f3cf3101158f4/std/http/server.ts#L262
https://github.com/denoland/deno/blob/55d2c6bd103879263c115fa5697f3cf3101158f4/std/http/server.ts#L125

$ deno run --allow-net hello_http.ts
http://localhost:8080/

実行時に--allow-netというオプション引数を付与しています。
denoはデフォルトでインターネット上からアクセスできません。ユーザーが許可しない限り、ネットワークにアクセスできないためセキュアです。

スクリーンショット 2018-12-31 09.41.11.png

ブラウザからlocalhost:8080にアクセスしてHello, Woldが表示されればWebサーバは起動しています。

あとがき

Deno は Node.js の反省点を踏まえて開発されており、かつとてもシンプルでセキュアなTypeScript 実行環境です。
1.0 が出るまでは Deno の変更点も多かったですが、1.0 がリリースされて今後もメジャーバージョンが上がるまで破壊的変更は起きないと思います。
しかし、今後も開発は盛んに行われていくと思いますし、利用頻度も増えコミュニティやエコシステムも成熟していくと考えています。これからの成長が楽しみです。

最後までお読みいただきありがとうございます。質問や不備があればTwitter(@shisama_)またはコメント欄までお願いいたします。

この記事は 2020-05-14 に大幅更新しています。

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
9