Logicoya
HOME › オンライン教材 › Node.js超入門 › Lesson 3 Webサーバ
3

Webサーバ

Node.js の Webサーバー

JavaScript でプログラミング

通常、Web サーバーを構築する場合は、Apache や Nginx といったサービスを Linux にインストールして利用します。Node.js では、JavaScript で Web サーバーを独自に構築できます。サーバーサイドも JavaScript で書けるため、学習コストが比較的低いのが特徴です。

Node.js サーバの特徴

Node.js の Web サーバーは、軽量な処理を大量のアクセスに対応させながら、サーバーへの負荷を抑えて動作します。これを支えているのが、ノンブロッキングI/O と イベントループ です。開発では イベントドリブン(イベント駆動型) と呼ばれる手法でプログラミングします。

ノンブロッキングI/O

ノンブロッキングI/O は、シングルスレッドで複数の処理を進める仕組みです。I/O は、コンピュータの情報の入出力(Input / Output)のことです。

I/O の処理待ちが発生しても、すぐに関数が反応を返すため、待っている間に他の処理を進められます。

方式処理の進め方
ブロッキング1つ1つ順番に実行し、完了まで次の処理を待機
ノンブロッキング処理待ちの間も、他の処理を進行

参考:Node.js:ブロッキングとノンブロッキングの概要

イベントループ

イベントループ は、ノンブロッキングI/Oを効率よく実行する仕組みです。サーバーが起動すると同時にイベントを待機する状態になり、リクエストが届くたびに JavaScript のイベントハンドラを実行します。

手順内容
1タイマーのスケジュール設定
2イベントのコールバックをキューに追加
3コールバックの実行
4次のコールバックのチェックとクローズ

非同期処理との違い

似た仕組みに 非同期処理 があります。非同期処理 は、I/O の完了時に通知を受け取り、完了通知があるまでの間は他の処理を進められます。

シンプルなサーバの作成

Node.js に標準搭載されている http モジュールを使って、Web サーバーのリクエストとレスポンスを処理します。

ファイル構成

この教材で作成するファイルは、次のとおりです。

node_server/
├── package.json
├── simple_server.js
├── html_server.js
└── public/
    ├── index.html
    ├── about.html
    ├── hello.php
    ├── hello.py
    └── js/
        └── app.js
ファイル内容
simple_server.jsJSON を返すシンプルなサーバ
html_server.jsHTML などのファイルを返す静的ファイルサーバ
public/ブラウザに公開するファイルの保存場所

まずは node_server フォルダを作成して VSCode で開き、simple_server.js を作成します。

プロジェクトの準備

npm コマンドでプロジェクトを初期化します。

ターミナル
npm init -y

この教材のコードは import 文(ES Modules)で書くため、package.json に "type": "module" を追加します。

package.json
{
  "name": "node_server",
  "version": "1.0.0",
  "type": "module",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  }
}

"type": "module" がないプロジェクトでは、require() で読み込む CommonJS 形式になります。

http モジュール

http モジュールを読み込みます。

simple_server.js
import http from "http";

ホストとポートの設定

サーバーの待機先となるホスト名とポート番号を、定数に設定します。

simple_server.js
const HOST = "localhost";
const PORT = 3000;
項目値内容
ホストlocalhost自分のコンピュータ
ポート3000サーバーの受付番号

サーバの作成

http.createServer() でサーバーを作成します。コールバック関数の引数から、リクエスト(req)とレスポンス(res)のオブジェクトが利用できます。

simple_server.js
const server = http.createServer((req, res) => {

});
引数内容
reqブラウザからのリクエスト情報
resブラウザへ返すレスポンスの操作

ヘッダの出力

writeHead() で、ステータスコードとヘッダを出力します。この例では、成功を示す 200 と、JSON を返すことを示す Content-Type を設定します。

simple_server.js
res.writeHead(200, { "Content-Type": "application/json; charset=utf-8" });
ステータスコード意味
200成功
404ファイルが存在しない
500サーバ内部のエラー

レスポンスデータの作成

レスポンスで返すデータを、オブジェクトで作成します。JSON.stringify() で、オブジェクトを JSON 形式の文字列に変換します。

simple_server.js
const data = {
    message: "Hello, Node Server!",
    time: new Date().toISOString(),
};
const json = JSON.stringify(data, null, 2);
引数内容
data変換するオブジェクト
null変換対象を絞る指定(今回は不要)
2インデントのスペース数

レスポンスの書き込みと終了

write() でレスポンスの本文を書き込み、end() でレスポンスを終了します。end() を呼ばないと、ブラウザは応答の完了を待ち続けます。

simple_server.js
res.write(json);
res.end();

res.end(json) のように、end() に本文を渡して書き込みと終了を一度に行うこともできます。

サーバの待機

listen() でサーバーを待機させ、クライアントからのリクエストを待ちます。

simple_server.js
server.listen(PORT, HOST, () => {
    console.log(`Server running at http://${HOST}:${PORT}`);
});

ソース

simple_server.js の全体は、次のとおりです。

simple_server.js
import http from "http";

const server = http.createServer((req, res) => {
    res.writeHead(200, { "Content-Type": "application/json; charset=utf-8" });

    const data = {
        message: "Hello, Node Server!",
        time: new Date().toISOString(),
    };
    const json = JSON.stringify(data, null, 2);

    res.write(json);
    res.end();
});

const HOST = "localhost";
const PORT = 3000;

server.listen(PORT, HOST, () => {
    console.log(`Server running at http://${HOST}:${PORT}`);
});

サーバの起動と確認

サーバの起動

VSCode のターミナルで simple_server.js を実行します。サーバーが起動すると、ホスト localhost、ポート 3000 の localhost:3000 が待機アドレスになります。

ターミナル
node simple_server.js
結果
Server running at http://localhost:3000

ブラウザで確認

ブラウザで http://localhost:3000 にアクセスします。JSON が表示されれば成功です。

結果
{
  "message": "Hello, Node Server!",
  "time": "2026-11-04T06:21:43.740Z"
}

time は、アクセスするたびに現在の日時に変わります。

curl で確認

ターミナルの curl コマンドでも確認できます。-i を付けると、ステータスコードとヘッダも表示されます。

ターミナル
curl -i http://localhost:3000
結果
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
...

{
  "message": "Hello, Node Server!",
  "time": "2026-11-04T06:21:43.740Z"
}

サーバの停止

サーバーの停止は、起動中のターミナルで Ctrl + C を入力します。

開発用の起動(watch)

ソースコードを修正するたびに、Ctrl + C で停止して再起動するのは手間がかかります。ファイルの変更を監視して自動で再起動する watch モードで起動すると、開発が快適になります。

node の watch オプション

Node.js 18.11 以降では、--watch オプションが標準で使えます。追加のパッケージは不要です。

ターミナル
node --watch simple_server.js

ファイルを保存するたびに、サーバーが自動で再起動します。

npm run dev で起動

起動コマンドを scripts に登録すると、npm run で起動できます。

package.json
"scripts": {
  "simple": "node --watch simple_server.js",
  "dev": "node --watch html_server.js"
},
ターミナル
npm run simple
npm run dev
コマンド内容
npm run simplesimple_server.js を watch で起動
npm run devhtml_server.js を watch で起動

npm run dev は、次の章で作成する html_server.js ができてから実行します。

静的ファイルサーバの作成

次は、HTML、CSS、JavaScript、画像などのファイルを返す静的ファイルサーバを作成します。ブラウザが要求した URL に対応するファイルを、public フォルダから探して返します。

public フォルダの準備

public フォルダを作成し、ブラウザに公開するファイルを配置します。

public/
├── index.html
├── about.html
└── js/
    └── app.js
public/index.html
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8" />
    <title>Node Server(HTML)</title>
</head>
<body>
    <h1>Node Server</h1>
    <p>Node.js の簡易Webサーバへようこそ!</p>
    <a href="/about.html">About ページへ</a>

    <p id="message"></p>
    <script src="/js/app.js"></script>
</body>
</html>

実際の教材ファイルは、TailwindCSS でデザインしています。ここでは、サーバーの動作に必要な部分だけを示しています。

モジュールの読み込み

html_server.js を作成し、必要なモジュールを読み込みます。

html_server.js
import http from "http";
import fs from "fs";
import path from "path";
import url from "url";
import { exec } from "child_process";
モジュール用途
httpWebサーバの作成
fsファイルの存在確認と読み込み
pathファイルパスの組み立て
urlURLの解析
child_processOSコマンドの実行(番外編)

定数と公開ディレクトリ

ホスト、ポート、公開ディレクトリのパスを設定します。

html_server.js
const HOST = "localhost";
const PORT = 3000;

const __dirname = path.resolve();
const publicDir = path.join(__dirname, "public");
項目内容
path.resolve()現在のフォルダの絶対パス
path.join()パスをOSに合わせて連結
publicDir公開ファイルを保存するフォルダのパス

ES Modules では __dirname が用意されていないため、path.resolve() で代用しています。node コマンドを実行したフォルダが基準になるため、プロジェクトのフォルダで実行してください。

MIME タイプの設定

ブラウザは、Content-Type ヘッダの MIME タイプを見て、ファイルの種類を判断します。拡張子と MIME タイプの対応表を、オブジェクトで用意します。

html_server.js
const mimeTypes = {
    ".html": "text/html; charset=utf-8",
    ".css": "text/css; charset=utf-8",
    ".js": "application/javascript; charset=utf-8",
    ".png": "image/png",
    ".jpg": "image/jpeg",
    ".jpeg": "image/jpeg",
    ".gif": "image/gif",
    ".svg": "image/svg+xml",
};
拡張子ファイルの種類
.htmlHTML
.cssスタイルシート
.jsJavaScript
.png .jpg .gif画像
.svgベクター画像

サーバの作成

http.createServer() でサーバーを作成します。以降の処理は、このコールバック関数の中に記述します。

html_server.js
const server = http.createServer((req, res) => {

});

URL の解析

url.parse() でリクエストの URL を解析し、pathname(パス部分)を取得します。/ にアクセスされた場合は、/index.html として扱います。

html_server.js
const parsed = url.parse(req.url);
let pathname = parsed.pathname;
console.log(`pathname: ${pathname}`);

if (pathname === "/") pathname = "/index.html";
URLpathname
http://localhost:3000//
http://localhost:3000/about.html/about.html
http://localhost:3000/about.html?id=1/about.html

url.parse() は、最近の Node.js では非推奨の警告が表示されます。新しい書き方は new URL(req.url, "http://localhost").pathname です。

ファイルの存在確認(404)

path.join() で公開フォルダとパスを連結し、アクセスされたファイルの絶対パスを求めます。fs.existsSync() でファイルの存在を確認し、存在しなければ 404 を返します。

html_server.js
const filePath = path.join(publicDir, pathname);

if (!fs.existsSync(filePath)) {
    res.writeHead(404, { "Content-Type": "text/plain; charset=utf-8" });
    res.end("404 Not Found\n");
    return;
}

ファイルの読み込み(500)

fs.readFile() でファイルを読み込みます。読み込みに失敗したときは、サーバー内部のエラーを示す 500 を返します。

html_server.js
fs.readFile(filePath, (err, data) => {
    if (err) {
        res.writeHead(500, { "Content-Type": "text/plain; charset=utf-8" });
        res.end("500 Internal Server Error\n");
        return;
    }

});

MIME タイプの判定とレスポンス(200)

path.extname() で拡張子を取得し、mimeTypes から MIME タイプを選びます。対応表にない拡張子は、application/octet-stream(バイナリデータ)として扱います。最後に、ファイルの中身をレスポンスします。

html_server.js
const ext = path.extname(filePath).toLowerCase();
const mime = mimeTypes[ext] || "application/octet-stream";

res.writeHead(200, { "Content-Type": mime });
res.end(data);

サーバの待機

simple_server.js と同様に、listen() でサーバーを待機させます。

html_server.js
server.listen(PORT, HOST, () => {
    console.log(`Server running at http://${HOST}:${PORT}`);
});

動作確認

html_server.js を実行して、ブラウザで確認します。

ターミナル
node html_server.js
URL結果
http://localhost:3000/index.html を表示
http://localhost:3000/about.htmlabout.html を表示
http://localhost:3000/nothing.html404 Not Found

ターミナルには、アクセスした pathname がログ表示されます。

結果
Server running at http://localhost:3000
pathname: /
pathname: /about.html
pathname: /nothing.html

ブラウザ側の JavaScript

public/js/app.js は、ブラウザ上で動作する JavaScript です。Node.js ではなく、ブラウザが html_server.js から取得して実行します。

画面の書き換え

index.html と about.html に用意した id="message" の要素に、文字を表示します。

public/js/app.js
document.getElementById("message").textContent = "ここはJSで処理しました!";

/js/app.js へのリクエストも、html_server.js が application/javascript として返しています。

ファイル一覧の取得

fetch() でサーバーの /api/list にアクセスし、JSON を受け取って画面に一覧表示します。/api/list は、次の番外編で作成します。

public/js/app.js
async function loadFileList() {
    const listElem = document.getElementById("file-list");

    try {
        const res = await fetch("/api/list");
        if (!res.ok) throw new Error("通信エラー");

        const data = await res.json();

        listElem.innerHTML = "";

        if (!data.files || data.files.length === 0) {
            listElem.innerHTML = `<li class="text-gray-400 italic">ファイルがありません</li>`;
            return;
        }

        data.files.forEach((file) => {
            const li = document.createElement("li");
            li.className = "border-b list-none py-1";
            li.innerHTML = file;
            listElem.appendChild(li);
        });
    } catch (err) {
        listElem.innerHTML = `<li class="text-red-500">エラー: ${err.message}</li>`;
    }
}
処理内容
fetch()サーバーへリクエストを送信
res.json()レスポンスを JSON として変換
createElement()一覧の項目(li)を作成
appendChild()項目を画面に追加

「リスト取得」ボタンから呼び出すため、index.html に次の要素を追加します。

public/index.html
<button onclick="loadFileList()">リスト取得</button>
<ul id="file-list"></ul>

番外編:サーバでコマンド実行

child_process モジュールの exec() を使うと、サーバー上で OS のコマンドを実行できます。exec() は、コマンドの結果を stdout(標準出力)で受け取ります。

書式
exec(コマンド, (err, stdout, stderr) => {
    // 処理
});
引数内容
err実行エラー
stdout標準出力(実行結果)
stderr標準エラー出力

ファイル一覧 API(/api/list)

/api/list にアクセスされたら、public フォルダ内のファイル名を JSON で返します。OS によってコマンドが異なるため、process.platform で切り替えます。

OSコマンド
Mac / Linuxls -1
Windowsdir /b

URLの解析の直後に、/api/list の判定を追加します。

html_server.js
if (pathname === "/api/list") {
    execLS(res);
    return;
}

ファイル一覧を返す execLS() 関数を作成します。コマンドの出力を行ごとに分割して、配列に変換します。

html_server.js
function execLS(res) {
    const command = process.platform === "win32" ? "dir /b" : "ls -1";

    exec(`${command} ${publicDir}`, (err, stdout, stderr) => {
        if (err) {
            res.writeHead(500, { "Content-Type": "application/json; charset=utf-8" });
            res.end(JSON.stringify({ error: stderr || err.message }));
            return;
        }

        const files = stdout.split(/\r?\n/).filter(Boolean);
        res.writeHead(200, { "Content-Type": "application/json; charset=utf-8" });
        res.end(JSON.stringify({ files }, null, 2));
    });
}

http://localhost:3000/api/list にアクセスして、確認します。

結果
{
  "files": [
    "about.html",
    "hello.php",
    "hello.py",
    "index.html",
    "js"
  ]
}

index.html の「リスト取得」ボタンをクリックすると、app.js がこの JSON を取得して、画面にファイル一覧を表示します。

PHP と Python の実行

拡張子が .php または .py のファイルにアクセスされたら、ファイルの内容を返す代わりに、プログラムを実行して結果を返します。

php コマンドと python コマンドが、実行できる環境で試してください。

実行するプログラムを、public フォルダに作成します。

public/hello.php
<?php
echo("php コマンドで実行されました!");
?>
public/hello.py
print("python コマンドで実行されました!")

「MIME タイプの判定」の中で、拡張子を判定してプログラムを実行します。

html_server.js
if (ext === ".php" || ext === ".py") {
    execFile(ext, filePath, res);
    return;
}

拡張子に合わせてコマンドを選ぶ execFile() と、コマンドを実行して結果を返す execCommand() を作成します。

html_server.js
function execFile(ext, filePath, res) {
    if (ext === ".php") execCommand("php", filePath, res);
    if (ext === ".py") execCommand("python", filePath, res);
}

function execCommand(command, filePath, res) {
    exec(`${command} ${filePath}`, (err, stdout, stderr) => {
        if (err) {
            res.writeHead(500, { "Content-Type": "text/plain; charset=utf-8" });
            res.end(stderr);
            return;
        }
        res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
        res.end(stdout);
    });
}
URL結果
http://localhost:3000/hello.phpphp コマンドで実行されました!
http://localhost:3000/hello.pypython コマンドで実行されました!

このコードは学習用です。exec() にファイルパスをそのまま渡し、/../ のような URL による公開フォルダ外へのアクセスも防いでいません。インターネットに公開するサーバーでは使わないでください。

ソース

html_server.js の全体は、次のとおりです。

html_server.js
import http from "http";
import fs from "fs";
import path from "path";
import url from "url";
import { exec } from "child_process";

const HOST = "localhost";
const PORT = 3000;

const __dirname = path.resolve();
const publicDir = path.join(__dirname, "public");

const mimeTypes = {
    ".html": "text/html; charset=utf-8",
    ".css": "text/css; charset=utf-8",
    ".js": "application/javascript; charset=utf-8",
    ".png": "image/png",
    ".jpg": "image/jpeg",
    ".jpeg": "image/jpeg",
    ".gif": "image/gif",
    ".svg": "image/svg+xml",
};

const server = http.createServer((req, res) => {
    const parsed = url.parse(req.url);
    let pathname = parsed.pathname;
    console.log(`pathname: ${pathname}`);

    if (pathname === "/") pathname = "/index.html";

    if (pathname === "/api/list") {
        execLS(res);
        return;
    }

    const filePath = path.join(publicDir, pathname);

    if (!fs.existsSync(filePath)) {
        res.writeHead(404, { "Content-Type": "text/plain; charset=utf-8" });
        res.end("404 Not Found\n");
        return;
    }

    fs.readFile(filePath, (err, data) => {
        if (err) {
            res.writeHead(500, { "Content-Type": "text/plain; charset=utf-8" });
            res.end("500 Internal Server Error\n");
            return;
        }

        const ext = path.extname(filePath).toLowerCase();
        const mime = mimeTypes[ext] || "application/octet-stream";

        if (ext === ".php" || ext === ".py") {
            execFile(ext, filePath, res);
            return;
        }

        res.writeHead(200, { "Content-Type": mime });
        res.end(data);
    });
});

server.listen(PORT, HOST, () => {
    console.log(`Server running at http://${HOST}:${PORT}`);
});

function execFile(ext, filePath, res) {
    if (ext === ".php") execCommand("php", filePath, res);
    if (ext === ".py") execCommand("python", filePath, res);
}

function execLS(res) {
    const command = process.platform === "win32" ? "dir /b" : "ls -1";

    exec(`${command} ${publicDir}`, (err, stdout, stderr) => {
        if (err) {
            res.writeHead(500, { "Content-Type": "application/json; charset=utf-8" });
            res.end(JSON.stringify({ error: stderr || err.message }));
            return;
        }

        const files = stdout.split(/\r?\n/).filter(Boolean);
        res.writeHead(200, { "Content-Type": "application/json; charset=utf-8" });
        res.end(JSON.stringify({ files }, null, 2));
    });
}

function execCommand(command, filePath, res) {
    exec(`${command} ${filePath}`, (err, stdout, stderr) => {
        if (err) {
            res.writeHead(500, { "Content-Type": "text/plain; charset=utf-8" });
            res.end(stderr);
            return;
        }
        res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
        res.end(stdout);
    });
}

まとめ

項目内容
Node.js の WebサーバーJavaScript で構築できる軽量なサーバー
ノンブロッキングI/Oシングルスレッドで複数の処理を進める仕組み
イベントループノンブロッキングI/Oを効率よく実行する仕組み
http.createServer()サーバーの作成
req / resリクエスト情報とレスポンスの操作
writeHead() / write() / end()ヘッダ出力、本文の書き込み、レスポンス終了
listen()ホストとポートでの待機
JSON.stringify()オブジェクトから JSON 文字列への変換
node --watchファイル変更時の自動再起動
Content-Typeファイルの種類を伝えるヘッダ
200 / 404 / 500成功 / ファイルなし / サーバ内部エラー
fs.existsSync() / fs.readFile()ファイルの存在確認と読み込み
exec()サーバー上でのOSコマンド実行