This article explores several essential Node.js modules that provide system-level functionality and utilities. We'll examine the OS module for system information, the util module for various utility functions, and the dns module for domain name resolution.
OS Module The OS module in Node.js provides methods for retrieving information about the operating system.
const os = require('os');
// Returns a string pointing to the OS default temporary directory
console.log("Temporary directory: " + os.tmpdir());
// Returns BE or LE depending on the machine's architecture
console.log("Endianness: " + os.endianness());
// Returns the hostname of the machine
console.log("Hostname: " + os.hostname());
// Returns the operating system type
console.log("OS Type: " + os.type());
// Returns the platform name
console.log("Platform: " + os.platform());
// Returns the architecture
console.log("Architecture: " + os.arch());
// Returns the operating system release version
console.log("Release: " + os.release());
// Returns the system uptime in seconds
console.log("Uptime: " + os.uptime());
// On Unix systems, returns an array containing 1, 5, and 15 minute load averages
console.log("Load average: " + os.loadavg());
// Returns the total system memory in bytes
console.log("Total memory: " + os.totalmem());
// Returns the available system memory in bytes
console.log("Free memory: " + os.freemem());
// Contains the OS-specific line ending characters
console.log("Line ending: " + os.EOL);
// Returns an array of objects describing the CPU
console.log("CPU info: " + JSON.stringify(os.cpus()));
// Returns an array of network interface objects
console.log("Network interfaces: " + JSON.stringify(os.networkInterfaces()));
Temporary directory: C:\Users\ADMINI~1\AppData\Local\Temp
Endianness: LE
Hostname: Lenovo-PC
OS Type: Windows_NT
Platform: win32
Architecture: x64
Release: 10.0.10240
Uptime: 857903.0353439
Load average: 0,0,0
Total memory: 4202979328
Free memory: 609837056
Line ending:
CPU info: [{"model":"Intel(R) Core(TM) i5-4200M CPU @ 2.50GHz","speed":2494,"times":{"user":14228468,"nice":0,"sys":16551359,"idle":266524781,"irq":3004875}},{"model":"Intel(R) Core(TM) i5-4200M CPU @ 2.50GHz","speed":2494,"times":{"user":13634187,"nice":0,"sys":17665812,"idle":266004171,"irq":5612906}},{"model":"Intel(R) Core(TM) i5-4200M CPU @ 2.50GHz","speed":2494,"times":{"user":14396953,"nice":0,"sys":17213171,"idle":265694046,"irq":2041984}},{"model":"Intel(R) Core(TM) i5-4200M CPU @ 2.50GHz","speed":2494,"times":{"user":15294390,"nice":0,"sys":19912703,"idle":262097078,"irq":2563078}}]
Network interfaces: {"WLAN":[{"address":"fe80::ec29:33b8:7d3d:28e0","netmask":"ffff:ffff:ffff:ffff::","family":"IPv6","mac":"48:5a:b6:d5:44:8f","scopeid":16,"internal":false},{"address":"192.168.1.103","netmask":"255.255.255.0","family":"IPv4","mac":"48:5a:b6:d5:44:8f","internal":false}],"Loopback Pseudo-Interface 1":[{"address":"::1","netmask":"ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff","family":"IPv6","mac":"00:00:00:00:00:00","scopeid":0,"internal":true},{"address":"127.0.0.1","netmask":"255.0.0.0","family":"IPv4","mac":"00:00:00:00:00:00","internal":true}],"本地连接* 13":[{"address":"2001:0:5ef5:79fb:3079:3794:c272:4da6","netmask":"ffff:ffff:ffff:ffff::","family":"IPv6","mac":"00:00:00:00:00:00","scopeid":0,"internal":false},{"address":"fe80::3079:3794:c272:4da6","netmask":"ffff:ffff:ffff:ffff::","family":"IPv6","mac":"00:00:00:00:00:00","scopeid":9,"internal":false}]}
Process finished with exit code 0
Util Module The util module provides various utility functinos, including string formatting, type checking, and object inspection.
String Formatting
// util.format(format, [...])
// The util.format() method returns a formatted string based on the provided format string and arguments
// Placeholder types:
// %s: String
// %d: Number (integer or float)
// %j: JSON object
// %: If % is followed by nothing, it's not treated as a placeholder
// Important notes:
// 1. If there are more placeholders than arguments, extra placeholders remain unchanged
// 2. If there are more arguments than placeholders, extra arguments are appended as strings
// 3. If the first argument isn't a format string, all arguments are converted to strings and joined with spaces
const util = require('util');
let output = util.format('%s=%s', 'test');
console.log(output);
output = util.format('%s=%s', 'test');
console.log(output);
output = util.format('%s', 'test', 'example');
console.log(output);
output = util.format('1', 'test', 'example');
console.log(output);
% s=test
test=%s
test example
1 test example
Process finished with exit code 0
Type Checking The util module provides several functions for checking object types:
const util = require('util');
// Check if an array
const isArrayResult = util.isArray([1, 2, 3]);
console.log(isArrayResult);
// Check if null
const isNullResult = util.isNull(isArrayResult);
console.log(isNullResult);
// Check if Date object
const isDateResult = util.isDate(new Date());
console.log(isDateResult);
true
false
true
Process finished with exit code 0
Synchronous Output Writing The util module provides methods like debug(), error(), puts(), print(), and log() for writing synchronously to stdout and stderr. However, these methods are deprecated in favor of alternatives:
// Deprecated methods:
// 'util.exec is deprecated. Use child_process.exec instead.'
// 'util.print is deprecated. Use console.log instead.'
// 'util.puts is deprecated. Use console.log instead.'
// 'util.debug is deprecated. Use console.error instead.'
// 'util.error is deprecated. Use console.error instead.'
// 'util.pump is deprecated. Use readableStream.pipe instead.'
Converting Objects to Strings The util.inspect(object, [options]) method examines an object and returns its string representation. The options can include:
showHidden: When true, non-enumerable properties are also included depth: Limits the depth of inspection to prevent infinite recursion colors: When true, output uses ANSI color codes customInspect: When false, custom inspect functions on objects won't be called
const util = require('util');
const myObject = {
firstName: 'john',
lastName: 'doe'
};
// Add a custom inspect function
myObject.inspect = function(depth) {
return '{name: "' + this.firstName + ' ' + this.lastName + '"}';
};
console.log(util.inspect(myObject));
{name: "john doe"}
Process finished with exit code 0
DNS Module The DNS module enables domain name resolution, domain lookups, and reverse lookups. Common methods include:
lookup(domain, [family], callback): Resolves a domain name resolve(domain, [rrtype], callback): Resolves a domain name to specific record types resolve4(domain, callback): Resolves IPv4 addresses resolve6(domain, callback): Resolves IPv6 addresses resolveMX(domain, callback): Resolves mail exchange records resolveTxt(domain, callback): Resolves text records resolveSrv(domain, callback): Resolves SRV records resolveNs(domain, callback): Resolves name server records resolveCname(domain, callback): Resolves CNAME records reverse(ip, callback): Perofrms reverse IP lookup
const dns = require('dns');
console.log("Resolving www.example.com...");
dns.resolve4('www.example.com', function (err, addresses) {
if (err) {
console.error('Error resolving domain:', err);
return;
}
console.log('IPv4 addresses: ' + JSON.stringify(addresses, null, ' '));
addresses.forEach(function (addr) {
dns.reverse(addr, function (err, domains) {
if (err) {
console.log('Reverse for ' + addr + ': No domain found');
} else {
console.log('Reverse for ' + addr + ': ' + JSON.stringify(domains));
}
});
});
});
Resolving www.example.com...
IPv4 addresses: [
"93.184.216.34"
]
Reverse for 93.184.216.34: ["example.com"]
Process finished with exit code 0