以下のようなコマンドで動くnodejsのプログラムがあって、これを永続化させたいということがあった。
sudo npm run example -- examples/hoge.ts'
そこで以下のようなhoge.jsを用意した。
const { exec } = require('child_process'); // 実行したいコマンド const command = 'sudo npm run example -- examples/map3.ts'; // コマンドを実行するディレクトリ const directoryPath = './'; // コマンドを実行 exec(command, { cwd: directoryPath }, (error, stdout, stderr) => { if (error) { console.error(`exec error: ${error}`); return; } if (stdout) { console.log(`stdout: ${stdout}`); } if (stderr) { console.error(`stderr: ${stderr}`); } });
それを使って、PM2にhoge.jsを実行してもらう。
pm2 start hoge.js
止める/消す
pm2 delete process_name
それを保存
pm2 save --force