This commit is contained in:
2024-12-05 20:53:21 +08:00
parent a117281b9e
commit b631ff4a09
5 changed files with 74 additions and 11 deletions

View File

@@ -4,8 +4,8 @@ import path from 'path';
import fs from 'fs';
import { chalk } from '@/module/chalk.ts';
import inquirer from 'inquirer';
import { spawn } from 'child_process';
import { installDeps } from '@/uitls/npm.ts';
import { spawn, spawnSync } from 'child_process';
import { checkPm2, installDep, installDeps } from '@/uitls/npm.ts';
const command = new Command('init').description('初始化应用').action((optison) => {
console.log('init');
@@ -31,6 +31,7 @@ const initMain = async () => {
main: 'dist/app.mjs',
scripts: {
start: 'node dist/app.mjs',
pm2: 'pm2 start dist/app.mjs --name main-app',
},
dependencies: {
'@kevisual/router': 'latest',
@@ -118,6 +119,7 @@ const mainApp = new Command('main')
.option('-s, --start', '启动main应用')
.option('-r, --restart', '重启main应用')
.option('-e, --exit', '停止main应用')
.option('-p, --pm2', '使用pm2管理只作为启动')
.action(async (options) => {
if (options.init) {
await initMain();
@@ -142,13 +144,24 @@ const mainApp = new Command('main')
}
// 打开日志文件(追加模式)
const logStream = fs.openSync(logFile, 'a');
const childProcess = spawn('node', ['dist/app.mjs'], {
if (options.pm2) {
if (!checkPm2()) {
console.log('安装pm2');
installDep({ isGlobal: true, sync: true, dep: 'pm2' });
console.log(chalk.green('安装pm2成功'));
}
}
let comm = options.pm2 ? 'pm2' : 'node';
const args = options.pm2 ? ['start', 'dist/app.mjs', '--name', 'main-app'] : ['dist/app.mjs'];
const childProcess = spawn(comm, args, {
cwd: getConfig().mainAppPath,
stdio: ['ignore', logStream, logStream], // 忽略 stdio, 重定向到文件
detached: true, // 使子进程独立运行
});
childProcess.unref(); // 使子进程独立运行
writeConfig({ ...getConfig(), mainAppPid: childProcess.pid });
if (!options.pm2) {
writeConfig({ ...getConfig(), mainAppPid: childProcess.pid });
}
};
const config = getConfig();
if (!config.mainAppPath) {
@@ -180,9 +193,17 @@ const mainApp = new Command('main')
process.kill(config.mainAppPid);
}
writeConfig({ ...config, mainAppPid: null });
console.log('main app 已经停止');
}
}
});
const mainPathCommand = new Command('path').action(() => {
const config = getConfig();
const appPath = path.resolve(config.mainAppPath);
console.log(`cd ${appPath}`);
});
mainApp.addCommand(mainPathCommand);
const mainLogCommand = new Command('log')
.option('-t, --tail', '查看日志')