在 Node.js 中,有一些全局对象和变量是在任何地方都可访问的,而无需引入模块。以下是一些常见的 Node.js 全局对象和变量:

1. global 对象:

global 对象类似于浏览器中的 window 对象,是 Node.js 中的全局对象。在模块中,global 对象可以省略直接使用。
// 在模块中可以省略 global.
global.myVariable = 'This is a global variable';

// 在其他模块中可以访问 global 对象的属性
console.log(myVariable); // 输出: This is a global variable

2. process 对象:

process 对象提供了与当前 Node.js 进程相关的信息和控制功能。
console.log(process.pid); // 当前进程的 PID
console.log(process.cwd()); // 当前工作目录
console.log(process.version); // Node.js 版本

3. console 对象:

console 对象提供了控制台输出功能。
console.log('This is a log message');
console.error('This is an error message');

4. Buffer 类:

Buffer 类是 Node.js 中用于处理二进制数据的类。虽然 Buffer 类在每个模块中都可用,但它并不是全局对象的属性。
const buffer = Buffer.from('Hello, World!', 'utf-8');
console.log(buffer.toString()); // 输出: Hello, World!

5. __filename 和 __dirname 变量:

__filename 表示当前模块的文件名,__dirname 表示当前模块的目录名。
console.log(__filename); // 当前模块的文件名
console.log(__dirname); // 当前模块的目录名

6. 定时器函数:

setTimeout、setInterval 和 setImmediate 是一些用于处理定时任务的全局函数。
setTimeout(() => {
    console.log('Delayed message');
}, 1000);

setInterval(() => {
    console.log('Repeated message');
}, 2000);

setImmediate(() => {
    console.log('Immediate message');
});

7. require 函数:

require 函数是用于导入模块的函数,虽然它通常在模块中使用,但也可以在全局范围内使用。
const fs = require('fs');
const http = require('http');

以上是一些常见的 Node.js 全局对象和变量。需要注意的是,全局变量的过度使用可能导致命名冲突和代码不易维护。在实际开发中,通常更推荐使用模块化的方式,将变量和功能封装在模块内,以提高代码的可维护性和可重用性。


转载请注明出处:http://www.zyzy.cn/article/detail/13164/Node.js