はじめに
Node.jsの組み込みhttpモジュールを使ってTypeScriptで簡単なサーバーを作る機会があったので、紹介します。
Expressなどのフレームワークを使わずに、軽量なHTTPサーバーを構築したい場合に便利です。
実装例
以下は、URLパスに応じて異なるステータスコードとJSONレスポンスを返すシンプルなHTTPサーバーの実装例です。
import { createServer, IncomingMessage, ServerResponse } from 'http';
const PORT = 8080;
const server = createServer((req: IncomingMessage, res: ServerResponse) => {
res.setHeader('Content-Type', 'application/json');
if (req.url === '/success') {
res.statusCode = 200;
res.end(JSON.stringify({ message: 'OK', status: 200 }));
} else if (req.url === '/error') {
res.statusCode = 500;
res.end(JSON.stringify({ message: 'Internal Server Error', status: 500 }));
} else {
res.statusCode = 404;
res.end(JSON.stringify({ message: 'Not Found', status: 404 }));
}
});
server.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
動作確認
サーバーを起動後、以下のコマンドで動作確認できます:
# 成功レスポンス
curl http://localhost:8080/success
# エラーレスポンス
curl http://localhost:8080/error
# 404レスポンス
curl http://localhost:8080/other
環境
- Node.js: v20.15.1
- TypeScript: 5.5.3
- @types/node: 20.14.10