てけとーぶろぐ。

ソフトウェアの開発と、お絵かきと、雑記と。

Node.jsでJSONを返すHTTPサーバーを作る

最近TypeScriptでWebアプリを作っています。
そのなかで使ったことないけどAPIサーバーにNode.jsという選択はありかもなぁ。
本格的に使わなくともちょっとしたものを作るのに使えたらよさそう。
と思うようになりました。

以下の点でよさそうだと思っています。

  • サーバー側もJavaScriptやらTypeScriptで書ける
  • Web APIで使うJSONと相性がいい
  • 気になっているMongoDBと相性がいい
  • 認証などに使っているFirebaseと相性がいい

ということでちょっと使ってみることに。

本屋でピッタリな書籍を見つけました。これで学びました。

入門Node.jsプログラミング

入門Node.jsプログラミング

  • 作者:Jonathan Wexler
  • 出版社/メーカー: 翔泳社
  • 発売日: 2019/09/25
  • メディア: 単行本(ソフトカバー)

大体わかったので試しに以前Pythonで書いたJSONを返すサーバーをNode.jsで作ってみます。
publicディレクトリーにJSONファイルを置いておいて、例えば「test.json」を置いて
そのファイル名のURL、この例だと「localhost:3000/test」にアクセスすると「test.json」の内容が返ってきます。
Webアプリの開発中にWeb APIのモックなんかに使えるかと思います。

以下手順。

Node.jsのインストール

以下からNode.jsをダウンロードしてインストールします。
Node.js

アプリケーションの初期化

ディレクトリーを作って「npm init」

$ mkdir json_server
$ cd json_server/
$ npm init

各質問にはエンターキーでデフォルトを選んで行けば問題なしですが
「entry point:」に対しては「main.js」を指定します。

ライブラリーのインストール

必要なライブラリーをインストールします。

$ npm install express http-status-codes --save

簡単にWebサーバー、Webアプリが作れるexpressと
HTTPのステータスコードの定義が入ったhttp-status-codesです。

コードの作成

json_server/main.js を以下の内容で作ります。

const express = require("express");
const app = express();

const errorController = require("./controllers/errorController")
const jsonFileController = require("./controllers/jsonFileController")

app.set("port", process.env.PORT || 3000);

app.get(/\/.+/, jsonFileController.showJsonFile);

app.use(errorController.pageNotFoundError); 
app.use(errorController.internalServerError);

app.listen(app.get("port"), () => {
    console.log(`Server is running at http://localhost:${app.get("port")}`);
});

json_server/controllers/jsonFileController.js を以下の内容で作ります。

const fs = require("fs");
const path = require("path");

exports.showJsonFile = (req, res, next) => {
    const dirPath = 'public';
    fs.readdir(dirPath, function(err, files) {
        if (err) {
            next(err);
            return;
        }
        if (err) next(err);
        for (const file of files) {
            if (!fs.statSync(path.join(dirPath, file)).isFile() ||
                path.extname(file) !== ".json") {
                continue;
            }
            if (req.url !== '/' + path.basename(file, path.extname(file))) {
                continue;
            }
            fs.readFile(path.join(dirPath, file), (err, data) => {
                if (err) {
                    next(err);
                    return;
                }
                res.send(JSON.parse(data.toString()));
            });
            return;
        }
        next();
    });
};

json_server/controllers/errorController.js を以下の内容で作ります。
こいつはエラー処理に特に気を使わない場合は不要です。

const httpStatus = require("http-status-codes");

exports.pageNotFoundError = (req, res) => { 
    let errorCode = httpStatus.NOT_FOUND; 
    res.status(errorCode);
    res.send("Page not found");
};

exports.internalServerError = (error, req, res, next) => { 
    let errorCode = httpStatus.INTERNAL_SERVER_ERROR; 
    console.log(`Error occurred: ${error.stack}`);
    res.status(errorCode);
    res.send({ error: error });
};

json_server/public/test.json としてサンプルのjsonファイルを作ります。

{
    "message": "こんにちは"
}
実行

以下のコマンドで実行します。
終了するときは Ctrl+C です。

$ node .\main.js

使い始めのお作法が分かればあとは楽ちんですね。