Files
wwjcloud/src/common/system/system.utils.ts

171 lines
3.9 KiB
TypeScript
Raw Normal View History

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<string, any>();
// 模块名称常量
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<T = any>(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<string> {
return new Set(this.moduleMap.keys());
}
/**
*
* @param className
* @returns
*/
static forName<T = any>(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();
}
}