The global object in Node.js
Overview of Node.js Global Objects
In the Node.js runtime environment, there are some global objects that can be used directly without requiring them. These objects are shared across different modules and provide basic API functionality. Similar to the window
object in browsers, Node.js's global objects are specifically designed for server-side environments.
The global
Object
global
is the top-level global object in Node.js. All global variables (except module
itself) are properties of the global
object. In the REPL environment, you can view all properties by directly entering global
:
console.log(global.process === process); // true
console.log(global.setTimeout === setTimeout); // true
Key characteristics to note:
- Variables declared with
var
are not added to theglobal
object. - Variables declared with
let
orconst
do not appear on theglobal
object. - Assigning a value to an undeclared variable makes it a property of
global
.
var foo = 'var';
let bar = 'let';
baz = 'global';
console.log(global.foo); // undefined
console.log(global.bar); // undefined
console.log(global.baz); // 'global'
The process
Object
The process
object provides an interface for interacting with the current Node.js process. Common functionalities include:
Environment Variable Operations
// Get environment variables
console.log(process.env.PATH);
// Set environment variables
process.env.NODE_ENV = 'production';
Process Control
// Exit the process
process.exit(1);
// Listen for exit events
process.on('exit', (code) => {
console.log(`Exit code: ${code}`);
});
Standard Input/Output
process.stdin.on('data', (data) => {
process.stdout.write(`Received: ${data}`);
});
Performance Analysis
// Memory usage
console.log(process.memoryUsage());
// CPU usage
console.log(process.cpuUsage());
The console
Object
Node.js's console
is similar to the browser's but has some extensions:
Formatted Output
console.log('Count: %d', 10);
console.log('Object: %j', {key: 'value'});
Timing Functions
console.time('loop');
for(let i=0; i<1000000; i++){}
console.timeEnd('loop'); // loop: 2.123ms
Stack Tracing
console.trace('Current location');
Timer-Related Functions
Node.js provides four types of timer functions:
// One-time timer
const timeout = setTimeout(() => {
console.log('Executes after 1 second');
}, 1000);
// Periodic timer
const interval = setInterval(() => {
console.log('Executes every second');
}, 1000);
// Immediate execution
const immediate = setImmediate(() => {
console.log('Executes in the next event loop');
});
// Clean up timers
clearTimeout(timeout);
clearInterval(interval);
clearImmediate(immediate);
The Buffer
Class
Buffer
is a global class for handling binary data:
// Create a Buffer
const buf1 = Buffer.alloc(10); // Initialize 10 bytes
const buf2 = Buffer.from('hello');
// Write data
buf1.write('Node.js');
// Read data
console.log(buf2.toString('utf8', 0, 2)); // 'he'
// Convert formats
const buf3 = Buffer.from('74657374', 'hex');
console.log(buf3.toString()); // 'test'
__filename
and __dirname
These variables provide information about the current module's file path:
console.log(__filename); // Absolute path of the current file
console.log(__dirname); // Absolute path of the current directory
// Example of path joining
const path = require('path');
const fullPath = path.join(__dirname, 'config.json');
module
, exports
, and require
Although they appear to be global variables, they are actually local to each module:
// Two ways to use module.exports
module.exports = { key: 'value' };
exports.key = 'value';
// Using require
const fs = require('fs');
const myModule = require('./my-module');
Other Important Global Objects
The URL
Class
const myURL = new URL('https://example.com/path?query=123');
console.log(myURL.searchParams.get('query')); // '123'
TextEncoder
/TextDecoder
const encoder = new TextEncoder();
const decoder = new TextDecoder();
const uint8Array = encoder.encode('Hello');
console.log(decoder.decode(uint8Array)); // 'Hello'
performance
const { performance } = require('perf_hooks');
performance.mark('start');
// Perform some operations
performance.mark('end');
performance.measure('Duration', 'start', 'end');
console.log(performance.getEntriesByName('Duration'));
Global Objects and the Module System
Node.js's module system affects the visibility of global variables:
- Each module has its own scope; variables declared with
var
do not polluteglobal
. - Modules loaded via
require
are cached in therequire.cache
object. - The true global object can be accessed via
globalThis
(ES2020 standard).
// Share data across modules
global.sharedData = { count: 0 };
// Check module cache
console.log(require.cache);
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn
下一篇:Node.js的REPL环境