やりたいこと
winser を使ってWindowsサービス化したNode.jsアプリケーションをバージョンアップして再起動したい
プロセスマネージャとかコンテナとかを使わずにアプリケーション自身で上記を行う(トリガは開発者が行う)
Node.jsのバージョンは12.xを使用
やったこと
準備
更新が必要なファイルをリストアップした設定ファイルを作っておく。
update.json
{
"files": [
"package.json",
"index.js"
]
}
バージョンアップ
nodegit を使って、Gitリポジトリにあるソースコードを一時フォルダにクローンする
index.js
const Git = require('nodegit').Clone;
const TEMP_DIR = __dirname + '/temp;
await Git.clone('path/to/repo', TEMP_DIR);
一時フォルダにあるファイルから必要なファイルをコピーする( 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
});
}
再起動
サービスの停止と起動を実行するコマンドをバッチファイルにしておく
restart.bat
call net stop %1
call npm install
call net start %1
exit
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
});
↧