過去ネタ供養 4:Node.js の標準モジュールだけで HTTP サーバを立てるコード片

過去ネタ供養シリーズ第4弾。Node.js の標準モジュール http だけを使って、超簡素な HTTP サーバを立てるコード片。

const port = process.env.PORT || 8080;
require('http').createServer((req, res) => {
  console.log(new Date(), req.url);
  res.writeHead(200, { 'Content-Type': 'text/html' });
  res.end('<!DOCTYPE html><html lang="ja"><head><meta charset="UTF-8"><title>Test</title></head><body><h1>Test</h1></body></html>');
}).listen(port);
console.log(`Server Started : Port [${port}]`);

環境変数 PORT で何も指定しなければ 8080 ポートでサーバが立ち上がり、どんなパスにアクセスしても「Test」と書かれた HTML が返るだけ。ちょっとした動作確認をしたい時によくこんなコードを書くので、スニペットとして残していた。

Deno だと

import { listenAndServe } from 'https://deno.land/std@0.113.0/http/server.ts';
await listenAndServe(':8080', (request: Request): Response => {
  return new Response('Hello World', { status: 200 });
});

もっと簡単になっていて、良いよね…。