ビール片手にプログラム ~ そうだ!遊ぼう! ~

ただ飲みながら遊んでいる話。まじめなこととかはしません。

TypeScriptを使用してNode.jsでhttpサーバーを建てて遊ぼう。

今回はTypeScriptを使用して、Node.jsでhttpサーバーを建てて遊ぼうと思います。 使用している各バージョンはこちらになります。
・node v12.3.1
・npm 6.9.0

1. 今日のお供

暑くなったりじめじめしてくると、日本酒の辛口が飲みたくなりますよね。
この日本酒は嘘偽り無く辛口なので冷やしてきりっと頂きます。 刈穂 山廃純米超辛口(刈穂酒造) 720ml

2. 今回参考にしたサイト

私はただ備忘録として、遊んだ結果を書きたいだけなので、本気でやりたい方はこちらを参考にされたほうが良いかと思います。

ics.media

3. TypeScriptプロジェクトの作成

プロジェクトフォルダを作成して、package.jsonを出力します。

mkdir node-type-server
cd node-type-server
npm init -y
npm i -D typescript

f:id:front-end:20190601203641p:plain
プロジェクトの作成

Node.jsの型定義ファイルを取得します。

npm i -S @types/node

f:id:front-end:20190601203929p:plain
Node.jsの型定義ファイルを取得

tsconfig.json(トランスパイル設定ファイル)を出力します。

node_modules\.bin\tsc --init 

f:id:front-end:20190601204357p:plain
tsconfig.jsonを出力

package.jsonを修正します。

{
  "name": "node-type-server",
  "version": "1.0.0",
  "private":true,
  "scripts": {
    "build": "tsc",
    "watch": "tsc --watch"
  },
  "devDependencies": {
    "typescript": "^3.5.1"
  },
  "dependencies": {
    "@types/node": "^12.0.4"
  }
}

f:id:front-end:20190601204725p:plain
package.json

tsconfig.json ファイルを修正します。

f:id:front-end:20190601205249p:plain
1~33行目
f:id:front-end:20190601212121p:plain
34~63行目

4. httpサーバーを建ててみよう

main.tsファイルを作成します。

import * as http from "http";

class Main {
    constructor() {
        // httpサーバーの設定をします。
        const server: http.Server = http.createServer(
            (
                request: http.IncomingMessage,
                response: http.ServerResponse
            ) => this.requestHandler(request, response)
        );

        // サーバーを起動します。
        server.listen('5000');
    }

    private requestHandler(request: http.IncomingMessage, 
                           response: http.ServerResponse): void {
        response.end("Hello! Node.js With TypeScript!")
    }
}

const main = new Main();

コンパイルを実行します。

npm run build

f:id:front-end:20190601212848p:plain
コンパイルの実行

コンパイルされたmain.jsをコマンドで実行します。

node main.js

f:id:front-end:20190601213124p:plain
main.js実行

http://localhost:5000にアクセスすると。。

f:id:front-end:20190601213214p:plain
表示されました!

5. TypeScriptを使用して、Node.jsでhttpサーバーを建てれました!

表示的にはシンプルなものですが、一応httpサーバーとしての役割を果たせました。
次回はAngular.js絡めるか、もうすこし深くnode.jsを触れたらよいなと思います。