まー、[Node.js] Webサーバを作る。(1)が古くなったんで書き直してみる。

プロジェクトのフォルダを作成する。
package.jsonを作成する。

$ npm init

まー、適当にエンターを押してデフォルトで作成する。
Node.jsの型定義ファイルをインストールする。

$ npm install @types/node --save

package.jsonのscriptsに"build"、"start"を追加、mainのJavascriptファイルなんかを変更しておく。
最終的にはこんな感じに。

{
  "name": "webserver2",
  "version": "1.0.0",
  "description": "",
  "main": "./js/webserver.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "tsc",
    "start": "node ./js/webserver.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@types/node": "^8.0.20"
  }
}

つぎに、Typescriptの設定ファイル(tsconfig.json)を作成する。

$ tsc --init

いろいろ編集してこんな感じに(デフォルト値のコメントは削除してある)

{
  "compilerOptions": {
    /* Basic Options */
    "target": "es5",                          /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'. */
    "module": "commonjs",                     /* Specify module code generation: 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
    "sourceMap": true,                     /* Generates corresponding '.map' file. */
    "outDir": "./js",                        /* Redirect output structure to the directory. */
    "strict": true                            /* Enable all strict type-checking options. */
  }
}

次に、ソースファイル(./src/webserver.ts)はこんな感じ。

// 簡単なWebサーバーだ(よく、サンプルとしてあるやつ)
import * as http from "http";	// (1)

var server = http.createServer((req, res):void => {
	res.writeHead(200, { "Content-Type": "text/plain" });
	res.write("Hello World!!\n");
	res.end();
});	// (2)
server.listen(9999);	// (3)

これで、

$ npm run build

でビルドして

$ npm run start

で実行する。

Webブラウザでhttp://localhost:9999にアクセスすると"Hello World!!"と表示される。

簡単なソースの説明
(1)で"http"のモジュールを読み込む。
(2)でhttpサーバーを生成。このWebサーバにアクセスした時に実行される関数をわたす。
関数の内容は、plainテキストでHello World!!を返す処理になっている。
(3)でポート番号9999で待ち受ける。