Search K
Appearance
Appearance
📊 SEO元描述:2024年最新Node.js全局对象教程,详解global对象、process进程管理、__dirname/__filename路径、Buffer二进制处理。包含完整代码示例,适合Node.js开发者掌握核心全局API。
核心关键词:Node.js全局对象、global对象、process对象、Buffer类、__dirname __filename、Node.js进程管理
长尾关键词:Node.js全局变量怎么用、process对象详解、Buffer二进制数据处理、Node.js路径获取、进程环境变量管理
通过本节Node.js全局对象和变量的学习,你将系统性掌握:
什么是global对象?它与浏览器的window有什么区别?global对象是Node.js中的全局作用域根对象,类似于浏览器中的window对象。但与浏览器不同,Node.js的global对象主要用于服务器端全局状态管理和模块间数据共享。
💡 使用原则:虽然global对象提供了全局访问能力,但应该谨慎使用,避免过度依赖全局状态,优先考虑模块化设计。
// 🎉 global对象完整使用示例
// === 基础global对象操作 ===
// 1. 检查global对象
console.log('=== global对象基础信息 ===');
console.log('global对象类型:', typeof global);
console.log('global === globalThis:', global === globalThis);
// 2. 设置全局变量
global.APP_NAME = 'Node.js学习应用';
global.APP_VERSION = '1.0.0';
global.APP_START_TIME = new Date();
// 3. 全局配置对象
global.AppConfig = {
environment: process.env.NODE_ENV || 'development',
port: process.env.PORT || 3000,
database: {
host: process.env.DB_HOST || 'localhost',
port: process.env.DB_PORT || 5432,
name: process.env.DB_NAME || 'myapp'
},
features: {
logging: true,
caching: true,
monitoring: true
}
};
// 4. 全局工具函数
global.utils = {
// 格式化日期
formatDate: (date = new Date()) => {
return date.toISOString().split('T')[0];
},
// 生成唯一ID
generateId: () => {
return Math.random().toString(36).substr(2, 9);
},
// 深度克隆对象
deepClone: (obj) => {
return JSON.parse(JSON.stringify(obj));
},
// 延迟执行
delay: (ms) => {
return new Promise(resolve => setTimeout(resolve, ms));
},
// 格式化文件大小
formatFileSize: (bytes) => {
const sizes = ['Bytes', 'KB', 'MB', 'GB'];
if (bytes === 0) return '0 Bytes';
const i = Math.floor(Math.log(bytes) / Math.log(1024));
return Math.round(bytes / Math.pow(1024, i) * 100) / 100 + ' ' + sizes[i];
}
};
// === 全局状态管理 ===
class GlobalStateManager {
static init() {
// 初始化全局状态
global.AppState = {
isInitialized: false,
startTime: Date.now(),
requestCount: 0,
errorCount: 0,
activeConnections: 0,
lastActivity: Date.now(),
// 统计信息
stats: {
totalRequests: 0,
totalErrors: 0,
averageResponseTime: 0,
peakMemoryUsage: 0
},
// 缓存
cache: new Map(),
// 事件监听器
listeners: new Map()
};
global.AppState.isInitialized = true;
console.log('✅ 全局状态管理器初始化完成');
}
// 增加请求计数
static incrementRequestCount() {
if (global.AppState) {
global.AppState.requestCount++;
global.AppState.stats.totalRequests++;
global.AppState.lastActivity = Date.now();
}
}
// 增加错误计数
static incrementErrorCount() {
if (global.AppState) {
global.AppState.errorCount++;
global.AppState.stats.totalErrors++;
}
}
// 更新连接数
static updateConnections(delta) {
if (global.AppState) {
global.AppState.activeConnections += delta;
global.AppState.activeConnections = Math.max(0, global.AppState.activeConnections);
}
}
// 获取状态报告
static getStatusReport() {
if (!global.AppState) {
return { error: '全局状态未初始化' };
}
const uptime = Date.now() - global.AppState.startTime;
const memoryUsage = process.memoryUsage();
return {
application: {
name: global.APP_NAME,
version: global.APP_VERSION,
environment: global.AppConfig.environment,
uptime: Math.round(uptime / 1000) + 's'
},
statistics: {
totalRequests: global.AppState.stats.totalRequests,
totalErrors: global.AppState.stats.totalErrors,
activeConnections: global.AppState.activeConnections,
errorRate: global.AppState.stats.totalRequests > 0
? (global.AppState.stats.totalErrors / global.AppState.stats.totalRequests * 100).toFixed(2) + '%'
: '0%'
},
memory: {
heapUsed: global.utils.formatFileSize(memoryUsage.heapUsed),
heapTotal: global.utils.formatFileSize(memoryUsage.heapTotal),
external: global.utils.formatFileSize(memoryUsage.external),
rss: global.utils.formatFileSize(memoryUsage.rss)
},
lastActivity: new Date(global.AppState.lastActivity).toISOString()
};
}
}
// === 全局缓存管理 ===
class GlobalCacheManager {
static set(key, value, ttl = 300000) { // 默认5分钟TTL
if (!global.AppState || !global.AppState.cache) {
console.warn('全局缓存未初始化');
return false;
}
const expireTime = Date.now() + ttl;
global.AppState.cache.set(key, {
value,
expireTime,
createdAt: Date.now()
});
console.log(`📦 缓存设置: ${key} (TTL: ${ttl}ms)`);
return true;
}
static get(key) {
if (!global.AppState || !global.AppState.cache) {
return null;
}
const cached = global.AppState.cache.get(key);
if (!cached) {
return null;
}
// 检查是否过期
if (Date.now() > cached.expireTime) {
global.AppState.cache.delete(key);
console.log(`🗑️ 缓存过期删除: ${key}`);
return null;
}
console.log(`📦 缓存命中: ${key}`);
return cached.value;
}
static delete(key) {
if (global.AppState && global.AppState.cache) {
const deleted = global.AppState.cache.delete(key);
if (deleted) {
console.log(`🗑️ 缓存删除: ${key}`);
}
return deleted;
}
return false;
}
static clear() {
if (global.AppState && global.AppState.cache) {
const size = global.AppState.cache.size;
global.AppState.cache.clear();
console.log(`🗑️ 清空缓存: ${size} 个条目`);
return size;
}
return 0;
}
static getStats() {
if (!global.AppState || !global.AppState.cache) {
return { size: 0, keys: [] };
}
const now = Date.now();
const entries = Array.from(global.AppState.cache.entries());
const validEntries = entries.filter(([key, data]) => now <= data.expireTime);
return {
size: global.AppState.cache.size,
validSize: validEntries.length,
expiredSize: entries.length - validEntries.length,
keys: validEntries.map(([key]) => key)
};
}
}
// === 全局事件系统 ===
class GlobalEventManager {
static emit(eventName, data) {
if (!global.AppState || !global.AppState.listeners) {
return false;
}
const listeners = global.AppState.listeners.get(eventName);
if (!listeners || listeners.length === 0) {
return false;
}
console.log(`📡 触发全局事件: ${eventName}`);
listeners.forEach(listener => {
try {
listener(data);
} catch (error) {
console.error(`全局事件监听器错误 (${eventName}):`, error.message);
}
});
return true;
}
static on(eventName, listener) {
if (!global.AppState || !global.AppState.listeners) {
console.warn('全局事件系统未初始化');
return false;
}
if (!global.AppState.listeners.has(eventName)) {
global.AppState.listeners.set(eventName, []);
}
global.AppState.listeners.get(eventName).push(listener);
console.log(`📡 注册全局事件监听器: ${eventName}`);
return true;
}
static off(eventName, listener) {
if (!global.AppState || !global.AppState.listeners) {
return false;
}
const listeners = global.AppState.listeners.get(eventName);
if (!listeners) {
return false;
}
const index = listeners.indexOf(listener);
if (index > -1) {
listeners.splice(index, 1);
console.log(`📡 移除全局事件监听器: ${eventName}`);
return true;
}
return false;
}
static getEventStats() {
if (!global.AppState || !global.AppState.listeners) {
return { events: 0, totalListeners: 0 };
}
const events = Array.from(global.AppState.listeners.entries());
const totalListeners = events.reduce((sum, [name, listeners]) => sum + listeners.length, 0);
return {
events: events.length,
totalListeners,
eventDetails: events.map(([name, listeners]) => ({
name,
listenerCount: listeners.length
}))
};
}
}
// === 全局错误处理 ===
global.ErrorHandler = {
// 记录错误
logError: (error, context = {}) => {
const errorInfo = {
message: error.message,
stack: error.stack,
timestamp: new Date().toISOString(),
context,
process: {
pid: process.pid,
memory: process.memoryUsage(),
uptime: process.uptime()
}
};
console.error('🚨 全局错误记录:', JSON.stringify(errorInfo, null, 2));
// 增加错误计数
GlobalStateManager.incrementErrorCount();
// 触发错误事件
GlobalEventManager.emit('error', errorInfo);
},
// 处理未捕获异常
handleUncaughtException: (error) => {
console.error('💥 未捕获异常:', error);
global.ErrorHandler.logError(error, { type: 'uncaughtException' });
// 优雅关闭
process.exit(1);
},
// 处理未处理的Promise拒绝
handleUnhandledRejection: (reason, promise) => {
console.error('💥 未处理的Promise拒绝:', reason);
global.ErrorHandler.logError(new Error(reason), {
type: 'unhandledRejection',
promise: promise.toString()
});
}
};
// 初始化全局系统
GlobalStateManager.init();
// 设置全局错误处理
process.on('uncaughtException', global.ErrorHandler.handleUncaughtException);
process.on('unhandledRejection', global.ErrorHandler.handleUnhandledRejection);
// 演示全局功能
console.log('\n=== 全局功能演示 ===');
// 缓存操作演示
GlobalCacheManager.set('user:123', { name: '张三', email: 'zhang@example.com' }, 10000);
GlobalCacheManager.set('config:app', { theme: 'dark', language: 'zh-CN' }, 20000);
const user = GlobalCacheManager.get('user:123');
console.log('缓存获取用户:', user);
const cacheStats = GlobalCacheManager.getStats();
console.log('缓存统计:', cacheStats);
// 事件系统演示
GlobalEventManager.on('user:login', (data) => {
console.log('用户登录事件:', data);
GlobalStateManager.incrementRequestCount();
});
GlobalEventManager.on('user:logout', (data) => {
console.log('用户登出事件:', data);
});
GlobalEventManager.emit('user:login', { userId: 123, timestamp: Date.now() });
// 状态报告
setTimeout(() => {
const statusReport = GlobalStateManager.getStatusReport();
console.log('\n=== 应用状态报告 ===');
console.log(JSON.stringify(statusReport, null, 2));
const eventStats = GlobalEventManager.getEventStats();
console.log('\n=== 事件系统统计 ===');
console.log(JSON.stringify(eventStats, null, 2));
}, 1000);
// 导出全局管理器(供其他模块使用)
if (typeof module !== 'undefined' && module.exports) {
module.exports = {
GlobalStateManager,
GlobalCacheManager,
GlobalEventManager
};
}process对象是Node.js中最重要的全局对象之一,提供了当前进程的信息和控制能力。
// 🎉 process对象完整使用示例
// === process基础信息 ===
console.log('\n=== process对象基础信息 ===');
// 1. 进程基本信息
const processInfo = {
// Node.js版本信息
nodeVersion: process.version,
versions: process.versions,
// 平台信息
platform: process.platform,
architecture: process.arch,
// 进程信息
processId: process.pid,
parentProcessId: process.ppid,
// 执行信息
execPath: process.execPath,
execArgv: process.execArgv,
argv: process.argv,
// 工作目录
currentWorkingDirectory: process.cwd(),
// 运行时间
uptime: process.uptime(),
// 用户信息
userInfo: process.getuid ? {
uid: process.getuid(),
gid: process.getgid(),
groups: process.getgroups ? process.getgroups() : 'N/A'
} : 'Windows系统不支持'
};
console.log('进程基础信息:', JSON.stringify(processInfo, null, 2));
// === 环境变量管理 ===
class EnvironmentManager {
// 获取环境变量
static get(key, defaultValue = null) {
return process.env[key] || defaultValue;
}
// 设置环境变量
static set(key, value) {
process.env[key] = value;
console.log(`🔧 设置环境变量: ${key} = ${value}`);
}
// 检查必需的环境变量
static checkRequired(requiredVars) {
const missing = [];
requiredVars.forEach(varName => {
if (!process.env[varName]) {
missing.push(varName);
}
});
if (missing.length > 0) {
throw new Error(`缺少必需的环境变量: ${missing.join(', ')}`);
}
console.log('✅ 所有必需的环境变量都已设置');
return true;
}
// 获取数据库配置
static getDatabaseConfig() {
return {
host: this.get('DB_HOST', 'localhost'),
port: parseInt(this.get('DB_PORT', '5432')),
database: this.get('DB_NAME', 'myapp'),
username: this.get('DB_USER', 'postgres'),
password: this.get('DB_PASSWORD', ''),
ssl: this.get('DB_SSL', 'false') === 'true'
};
}
// 获取服务器配置
static getServerConfig() {
return {
port: parseInt(this.get('PORT', '3000')),
host: this.get('HOST', '0.0.0.0'),
environment: this.get('NODE_ENV', 'development'),
logLevel: this.get('LOG_LEVEL', 'info'),
sessionSecret: this.get('SESSION_SECRET', 'default-secret'),
jwtSecret: this.get('JWT_SECRET', 'default-jwt-secret')
};
}
// 获取第三方服务配置
static getExternalServices() {
return {
redis: {
url: this.get('REDIS_URL', 'redis://localhost:6379'),
password: this.get('REDIS_PASSWORD', '')
},
email: {
service: this.get('EMAIL_SERVICE', 'gmail'),
user: this.get('EMAIL_USER', ''),
password: this.get('EMAIL_PASSWORD', '')
},
aws: {
accessKeyId: this.get('AWS_ACCESS_KEY_ID', ''),
secretAccessKey: this.get('AWS_SECRET_ACCESS_KEY', ''),
region: this.get('AWS_REGION', 'us-east-1')
}
};
}
// 显示环境配置摘要
static showConfigSummary() {
const summary = {
environment: this.get('NODE_ENV', 'development'),
port: this.get('PORT', '3000'),
database: {
host: this.get('DB_HOST', 'localhost'),
port: this.get('DB_PORT', '5432'),
name: this.get('DB_NAME', 'myapp')
},
features: {
ssl: this.get('ENABLE_SSL', 'false') === 'true',
clustering: this.get('ENABLE_CLUSTERING', 'false') === 'true',
monitoring: this.get('ENABLE_MONITORING', 'true') === 'true'
}
};
console.log('\n=== 环境配置摘要 ===');
console.log(JSON.stringify(summary, null, 2));
return summary;
}
}
// === 内存监控 ===
class MemoryMonitor {
constructor(interval = 5000) {
this.interval = interval;
this.monitoring = false;
this.history = [];
this.maxHistory = 100;
}
start() {
if (this.monitoring) {
console.log('内存监控已在运行');
return;
}
this.monitoring = true;
console.log('🔍 开始内存监控...');
this.timer = setInterval(() => {
this.collectMemoryData();
}, this.interval);
}
stop() {
if (!this.monitoring) {
console.log('内存监控未运行');
return;
}
this.monitoring = false;
clearInterval(this.timer);
console.log('🔍 停止内存监控');
}
collectMemoryData() {
const memoryUsage = process.memoryUsage();
const timestamp = Date.now();
const data = {
timestamp,
rss: memoryUsage.rss,
heapTotal: memoryUsage.heapTotal,
heapUsed: memoryUsage.heapUsed,
external: memoryUsage.external,
arrayBuffers: memoryUsage.arrayBuffers || 0
};
this.history.push(data);
// 保持历史记录在限制范围内
if (this.history.length > this.maxHistory) {
this.history.shift();
}
// 检查内存使用情况
this.checkMemoryThresholds(data);
}
checkMemoryThresholds(data) {
const heapUsedMB = data.heapUsed / 1024 / 1024;
const rssMB = data.rss / 1024 / 1024;
// 内存使用警告阈值
const heapWarningThreshold = 500; // 500MB
const rssWarningThreshold = 1000; // 1GB
if (heapUsedMB > heapWarningThreshold) {
console.warn(`⚠️ 堆内存使用过高: ${heapUsedMB.toFixed(2)}MB`);
}
if (rssMB > rssWarningThreshold) {
console.warn(`⚠️ RSS内存使用过高: ${rssMB.toFixed(2)}MB`);
}
}
getMemoryReport() {
if (this.history.length === 0) {
return { error: '没有内存监控数据' };
}
const latest = this.history[this.history.length - 1];
const oldest = this.history[0];
// 计算平均值
const avgHeapUsed = this.history.reduce((sum, data) => sum + data.heapUsed, 0) / this.history.length;
const avgRss = this.history.reduce((sum, data) => sum + data.rss, 0) / this.history.length;
// 计算峰值
const peakHeapUsed = Math.max(...this.history.map(data => data.heapUsed));
const peakRss = Math.max(...this.history.map(data => data.rss));
return {
current: {
heapUsed: `${(latest.heapUsed / 1024 / 1024).toFixed(2)}MB`,
heapTotal: `${(latest.heapTotal / 1024 / 1024).toFixed(2)}MB`,
rss: `${(latest.rss / 1024 / 1024).toFixed(2)}MB`,
external: `${(latest.external / 1024 / 1024).toFixed(2)}MB`
},
average: {
heapUsed: `${(avgHeapUsed / 1024 / 1024).toFixed(2)}MB`,
rss: `${(avgRss / 1024 / 1024).toFixed(2)}MB`
},
peak: {
heapUsed: `${(peakHeapUsed / 1024 / 1024).toFixed(2)}MB`,
rss: `${(peakRss / 1024 / 1024).toFixed(2)}MB`
},
monitoring: {
duration: `${((latest.timestamp - oldest.timestamp) / 1000).toFixed(0)}s`,
samples: this.history.length,
interval: `${this.interval}ms`
}
};
}
// 强制垃圾回收(需要--expose-gc标志)
forceGC() {
if (global.gc) {
const beforeGC = process.memoryUsage();
global.gc();
const afterGC = process.memoryUsage();
console.log('🗑️ 强制垃圾回收完成');
console.log(` 回收前堆内存: ${(beforeGC.heapUsed / 1024 / 1024).toFixed(2)}MB`);
console.log(` 回收后堆内存: ${(afterGC.heapUsed / 1024 / 1024).toFixed(2)}MB`);
console.log(` 回收内存: ${((beforeGC.heapUsed - afterGC.heapUsed) / 1024 / 1024).toFixed(2)}MB`);
return {
before: beforeGC,
after: afterGC,
freed: beforeGC.heapUsed - afterGC.heapUsed
};
} else {
console.warn('⚠️ 垃圾回收不可用,请使用 --expose-gc 标志启动Node.js');
return null;
}
}
}
// === 信号处理 ===
class SignalHandler {
constructor() {
this.shutdownCallbacks = [];
this.setupSignalHandlers();
}
setupSignalHandlers() {
// SIGINT (Ctrl+C)
process.on('SIGINT', () => {
console.log('\n📡 收到SIGINT信号 (Ctrl+C)');
this.gracefulShutdown('SIGINT');
});
// SIGTERM (终止信号)
process.on('SIGTERM', () => {
console.log('\n📡 收到SIGTERM信号');
this.gracefulShutdown('SIGTERM');
});
// SIGUSR1 (用户定义信号1)
process.on('SIGUSR1', () => {
console.log('\n📡 收到SIGUSR1信号 - 重新加载配置');
this.reloadConfiguration();
});
// SIGUSR2 (用户定义信号2)
process.on('SIGUSR2', () => {
console.log('\n📡 收到SIGUSR2信号 - 生成内存报告');
this.generateMemoryReport();
});
}
addShutdownCallback(callback) {
this.shutdownCallbacks.push(callback);
console.log('📝 添加关闭回调函数');
}
async gracefulShutdown(signal) {
console.log(`🔄 开始优雅关闭进程 (信号: ${signal})`);
try {
// 执行所有关闭回调
for (const callback of this.shutdownCallbacks) {
await callback();
}
console.log('✅ 优雅关闭完成');
process.exit(0);
} catch (error) {
console.error('❌ 优雅关闭失败:', error);
process.exit(1);
}
}
reloadConfiguration() {
// 重新加载配置的逻辑
console.log('🔄 重新加载应用配置...');
EnvironmentManager.showConfigSummary();
}
generateMemoryReport() {
// 生成内存报告
const memoryUsage = process.memoryUsage();
const report = {
timestamp: new Date().toISOString(),
memory: {
rss: `${(memoryUsage.rss / 1024 / 1024).toFixed(2)}MB`,
heapTotal: `${(memoryUsage.heapTotal / 1024 / 1024).toFixed(2)}MB`,
heapUsed: `${(memoryUsage.heapUsed / 1024 / 1024).toFixed(2)}MB`,
external: `${(memoryUsage.external / 1024 / 1024).toFixed(2)}MB`
},
process: {
pid: process.pid,
uptime: `${process.uptime().toFixed(2)}s`,
cpuUsage: process.cpuUsage()
}
};
console.log('📊 内存报告:');
console.log(JSON.stringify(report, null, 2));
}
}
// 使用示例
console.log('\n=== process对象功能演示 ===');
// 环境变量管理
EnvironmentManager.set('DEMO_VAR', 'demo_value');
console.log('获取环境变量:', EnvironmentManager.get('DEMO_VAR'));
EnvironmentManager.showConfigSummary();
// 内存监控
const memoryMonitor = new MemoryMonitor(2000);
memoryMonitor.start();
// 信号处理
const signalHandler = new SignalHandler();
signalHandler.addShutdownCallback(async () => {
console.log('🔄 关闭内存监控...');
memoryMonitor.stop();
});
signalHandler.addShutdownCallback(async () => {
console.log('🔄 清理全局缓存...');
GlobalCacheManager.clear();
});
// 5秒后显示内存报告
setTimeout(() => {
const memoryReport = memoryMonitor.getMemoryReport();
console.log('\n=== 内存监控报告 ===');
console.log(JSON.stringify(memoryReport, null, 2));
}, 5000);
// 导出模块
if (typeof module !== 'undefined' && module.exports) {
module.exports = {
EnvironmentManager,
MemoryMonitor,
SignalHandler
};
}通过本节Node.js全局对象和变量的学习,你已经掌握:
A: 谨慎使用global对象。适合用于应用级配置、工具函数、缓存等需要全局访问的场景。避免过度使用,优先考虑模块化设计和依赖注入。
A: 使用process.memoryUsage()获取内存信息,定期监控堆内存使用情况。可以设置阈值告警,必要时使用--expose-gc标志启用手动垃圾回收。
A: 监听SIGINT和SIGTERM信号,在信号处理器中执行清理工作(关闭数据库连接、保存状态等),然后调用process.exit()。
A: 使用.env文件存储开发环境变量,生产环境通过系统环境变量设置。验证必需的环境变量,提供合理的默认值,敏感信息不要提交到代码仓库。
A: 监听uncaughtException和unhandledRejection事件,记录错误信息,然后优雅关闭应用。但最好的做法是在代码中正确处理所有异常,避免未捕获异常的发生。
// 推荐的全局命名空间组织方式
global.MyApp = {
config: { /* 应用配置 */ },
utils: { /* 工具函数 */ },
cache: { /* 缓存管理 */ },
events: { /* 事件系统 */ },
state: { /* 应用状态 */ }
};// 进程健康检查端点
function healthCheck() {
const memoryUsage = process.memoryUsage();
const uptime = process.uptime();
return {
status: 'healthy',
uptime: `${uptime.toFixed(2)}s`,
memory: {
heapUsed: `${(memoryUsage.heapUsed / 1024 / 1024).toFixed(2)}MB`,
heapTotal: `${(memoryUsage.heapTotal / 1024 / 1024).toFixed(2)}MB`
},
timestamp: new Date().toISOString()
};
}"掌握Node.js全局对象是构建企业级应用的基础。global对象提供了全局状态管理能力,process对象让你能够控制和监控应用进程。合理使用这些全局API,能够让你的Node.js应用更加健壮和可维护。接下来,让我们深入学习文件系统模块!"