LoginSignup
0
0

More than 1 year has passed since last update.

サービス化したNode.jsアプリ自身にアップデート+再起動させる

Posted at

やりたいこと

  • winser を使ってWindowsサービス化したNode.jsアプリケーションをバージョンアップして再起動したい
  • プロセスマネージャとかコンテナとかを使わずにアプリケーション自身で上記を行う(トリガは開発者が行う)
  • Node.jsのバージョンは12.xを使用

やったこと

準備

更新が必要なファイルをリストアップした設定ファイルを作っておく。

update.json
{
  "files": [
    "package.json",
    "index.js"
  ]
}

バージョンアップ

  1. nodegit を使って、Gitリポジトリにあるソースコードを一時フォルダにクローンする

    index.js
    const Git = require('nodegit').Clone;
    const TEMP_DIR = __dirname + '/temp;
    await Git.clone('path/to/repo', TEMP_DIR);
    
  2. 一時フォルダにあるファイルから必要なファイルをコピーする( fs-extra を使用 )

    index.js
    const files = require(TEMP_DIR + '/update.json').files;
    const fs = require('fs-extra');
    for (const file of files) {
        fs.copySync(TEMP_DIR + '/' + file, __dirname + '/' + file, {
            overwrite: true
        });
    }
    

再起動

  1. サービスの停止と起動を実行するコマンドをバッチファイルにしておく

    restart.bat
    call net stop %1
    call npm install
    call net start %1
    exit
    
  2. child_process で再起動するためのコマンドを実行する。start コマンドを使ってさらに別のプロセスとしてサービスの停止~起動を実行するのがポイント

    index.js
    const { spawnSync } = require('child_process');
    const serviceName = require(__dirname + '/package.json').name;
    spawnSync('start', ['""', 'restart.bat', `"${serviceName}"`], {
        stdio: 'ignore',
        shell: true
    });
    
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0