GracefulShutdownManagerを使ってExpressサーバーを正常に終了させる

Node.jsのパッケージ、GracefulShutdownManagerを使って、コマンドプロントなどから強制終了した際にExpressサーバーを正常に終了させる方法です。

インストール

次のコマンドを実行してGracefulShutdownManagerをインストールします。

npm install @moebius/http-graceful-shutdown

使用方法

実際のソースコードに次のような内容を追記します。webServerhttps.createServer()などで作成したExpressのサーバーです。

// GracefulShutdownManager
const GracefulShutdownManager = require('@moebius/http-graceful-shutdown').GracefulShutdownManager;

// Windows用の処理.
if (process.platform === "win32") {
    console.log('windows platform');
    const readline = require("readline").createInterface({
        input: process.stdin,
        output: process.stdout
    });

    readline.on("SIGINT", () => {
        console.log('SIGINT (readline)');
        process.emit("SIGINT");
    });
}

const shutdownManager = new GracefulShutdownManager(webServer);
process.on('SIGINT', () => {
    console.log('SIGINT');
    shutdownManager.terminate(() => {
        console.log('Server is gracefully terminated.');
        process.exit();
    });
});

実行結果

サーバー起動中のコンソール・コマンドプロンプトで強制終了(Ctrl + C)した場合に表示されるログです。

Ubuntu の場合

SIGINT
Server is gracefully terminated.

Windowsの場合

SIGINT (readline)
SIGINT
Server is gracefully terminated.

参考

このエントリーをはてなブックマークに追加
にほんブログ村 IT技術ブログへ

スポンサードリンク

関連コンテンツ

コメント

メールアドレスが公開されることはありません。 が付いている欄は必須項目です