import { Injectable, Logger } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; /** * 系统工具类 * 基于 NestJS 实现 Java 风格的 SystemUtils * 对应 Java: SystemUtils */ @Injectable() export class SystemUtils { private readonly logger = new Logger(SystemUtils.name); private readonly moduleMap = new Map(); // 模块名称常量 static readonly I18N = 'i18n'; static readonly LOADER = 'loader'; static readonly CACHE = 'cache'; static readonly QUEUE = 'queue'; static readonly EVENT = 'event'; constructor(private readonly configService: ConfigService) { this.initializeModules(); } /** * 初始化模块 * 对应 Java: SystemUtils 构造函数 */ private initializeModules(): void { // 这里会在模块加载时注入相应的服务 this.logger.log('SystemUtils 模块初始化完成'); } /** * 注册模块 * @param name 模块名称 * @param module 模块实例 */ registerModule(name: string, module: any): void { this.moduleMap.set(name, module); this.logger.log(`注册模块: ${name}`); } /** * 获取模块 * @param name 模块名称 * @returns 模块实例 */ getModule(name: string): T | null { const module = this.moduleMap.get(name); if (!module) { this.logger.warn(`未找到模块: ${name}`); return null; } return module as T; } /** * 获取所有模块名称 * @returns 模块名称集合 */ getModuleNames(): Set { return new Set(this.moduleMap.keys()); } /** * 通过类名创建实例 * @param className 类名 * @returns 实例 */ static forName(className: string): T | null { try { // 在 Node.js 环境中,这需要动态导入 // 实际使用时需要根据具体需求实现 console.warn('forName 方法需要根据具体需求实现动态类加载'); return null; } catch (error) { console.error(`创建实例失败: ${className}`, error); return null; } } /** * 判断是否为 Windows 系统 * @returns 是否为 Windows */ static isWindowsOS(): boolean { return process.platform === 'win32'; } /** * 判断是否为 Linux 系统 * @returns 是否为 Linux */ static isLinuxOS(): boolean { return process.platform === 'linux'; } /** * 获取操作系统名称 * @returns 操作系统名称 */ static getOSName(): string { return process.platform; } /** * 重启应用 * 对应 Java: SystemUtils.restart() */ static restart(): void { try { if (SystemUtils.isWindowsOS()) { // Windows 重启脚本 const { exec } = require('child_process'); exec('restart.bat', (error: any) => { if (error) { console.error('重启失败:', error); } }); } else if (SystemUtils.isLinuxOS()) { // Linux 重启脚本 const { exec } = require('child_process'); exec('restart.sh', (error: any) => { if (error) { console.error('重启失败:', error); } }); } } catch (error) { console.error('重启应用失败:', error); } } /** * 获取系统信息 * @returns 系统信息 */ static getSystemInfo(): { platform: string; arch: string; nodeVersion: string; pid: number; uptime: number; } { return { platform: process.platform, arch: process.arch, nodeVersion: process.version, pid: process.pid, uptime: process.uptime(), }; } /** * 获取内存使用情况 * @returns 内存使用情况 */ static getMemoryUsage(): NodeJS.MemoryUsage { return process.memoryUsage(); } /** * 获取 CPU 使用情况 * @returns CPU 使用情况 */ static getCPUUsage(): NodeJS.CpuUsage { return process.cpuUsage(); } }