Node.js os Module
Node.js'sosos module is a built-in core module that provides practical methods and properties related to the operating system. Through this module, we can obtain various information about the operating system on which Node.js is currently running, such as CPU architecture, memory usage, network interfaces, etc.
Why do we need the os module?
When developing applications, sometimes we need to perform different operations based on different operating system environments, or we need to monitor the system's resource usage.osThe os module provides us with this capability, allowing us to easily obtain this system information.
How to use the os module
To useosthe module, we first need to import it:
Introduction to common methods
1. Get operating system information
Example
console.log(os.type()); // Returns the operating system name, e.g., 'Linux', 'Darwin', 'Windows_NT'
console.log(os.arch()); // Returns the CPU architecture, e.g., 'x64', 'arm'
console.log(os.release()); // Returns the operating system version
2. Get memory information
Example
console.log(os.freemem()); // Returns the available system memory (bytes)
// Convert to MB for display
console.log(`Total memory: ${os.totalmem() / 1024 / 1024} MB`);
console.log(`Available memory: ${os.freemem() / 1024 / 1024} MB`);
3. Get CPU information
Example
console.log(os.loadavg()); // Returns the average load for 1, 5, and 15 minutes (Linux/Unix only)
// Get the number of CPU cores
console.log(`Number of CPU cores: ${os.cpus().length}`);
4. Get network interface information
Example
5. Get user-related information
Example
console.log(os.userInfo()); // Returns information about the current user
console.log(os.hostname()); // Returns the hostname of the operating system
Practical application examples
Example 1: System monitoring tool
Example
function systemMonitor() {
console.log('=== System monitoring ===');
console.log(`Operating system: ${os.type()} ${os.release()}`);
console.log(`CPU architecture: ${os.arch()}`);
console.log(`Number of CPU cores: ${os.cpus().length}`);
console.log(`Total memory: ${(os.totalmem() / 1024 / 1024).toFixed(2)} MB`);
console.log(`Available memory: ${(os.freemem() / 1024 / 1024).toFixed(2)} MB`);
console.log(`System uptime: ${(os.uptime() / 60 / 60).toFixed(2)}hours`);
}
systemMonitor();
Example 2: Get network IP address
Example
function getLocalIP() {
const interfaces = os.networkInterfaces();
for (const interfaceName in interfaces) {
for (const iface of interfaces[interfaceName]) {
if (iface.family === 'IPv4' && !iface.internal) {
return iface.address;
}
}
}
return '127.0.0.1';
}
console.log(`Local IP address: ${getLocalIP()}`);
Notes
osThe information provided by the os module is read-only and cannot be used to modify system configuration.- The information returned by different operating systems may vary, especially between Windows and Unix-like systems.
- Some methods (such as
loadavg()) may not be available on Windows or may return different values. - Memory information is returned in bytes and usually needs to be converted to more readable units (such as MB or GB).
Methods
| Method | Description | Example |
|---|---|---|
os.arch() | Returns the CPU architecture of the operating system. | console.log(os.arch()); // 输出:'x64' |
os.constants | Returns an object containing operating system-specific constants (such as error codes, signals, etc.). | console.log(os.constants.signals); |
os.cpus() | Returns an array of objects, each containing information about a CPU core, such as model, speed, usage, etc. | console.log(os.cpus()); |
os.endianness() | Returns the CPU byte order (BEmeans big-endian byte order,LEmeans little-endian byte order). | console.log(os.endianness()); // 输出:'LE' |
os.freemem() | Returns the amount of free memory of the system (in bytes), which can be used to monitor system resources. | console.log(os.freemem()); |
os.homedir() | Returns the home directory path of the current user. | console.log(os.homedir()); |
os.hostname() | Returns the hostname. | console.log(os.hostname()); |
os.loadavg() | Returns an array containing the average load for 1, 5, and 15 minutes, only valid on Unix systems. | console.log(os.loadavg()); |
os.networkInterfaces() | Returns an object containing address information for each network interface, such asIP 地址、MAC 地址。 | console.log(os.networkInterfaces()); |
os.platform() | Returns the operating system platform, such as'darwin'、'win32'、'linux'etc. | console.log(os.platform()); |
os.release() | Returns the distribution version of the operating system. | console.log(os.release()); |
os.tmpdir() | Returns the default temporary file directory path of the operating system. | console.log(os.tmpdir()); |
os.totalmem() | Returns the total system memory (in bytes). | console.log(os.totalmem()); |
os.type() | Returns the name of the operating system, such as'Linux'、'Darwin'(macOS)、'Windows_NT'etc. | console.log(os.type()); |
os.uptime() | Returns the operating system uptime, in seconds. | console.log(os.uptime()); |
os.userInfo([options]) | Returns detailed information about the current user, such as username, home directory, UID, GID, etc. Supports configuring an options object to set the character encoding (default is'utf8')。 | console.log(os.userInfo()); |
Properties
| Property | Description | Example |
|---|---|---|
os.EOL | Returns the end-of-line marker for the current operating system (\nor\r\n), convenient for handling cross-platform file reading and writing. | console.log(os.EOL); // Windows 输出:'\r\n',Linux 输出:'\n' |
Example
Create a main.js file with the following code:
Example
// Get system architecture
console.log('System architecture:', os.arch());
// Get CPU information
console.log('CPU information:', os.cpus());
// Get free memory
console.log('Free memory:', os.freemem());
// Get total memory
console.log('Total memory:', os.totalmem());
// Get home directory
console.log('Home directory:', os.homedir());
// Get system platform
console.log('System platform:', os.platform());
// Get system name
console.log('System name:', os.type());
// Get average load (only applies to Unix systems)
console.log('Average load:', os.loadavg());
// Get network interface information
console.log('Network interface information:', os.networkInterfaces());
The code execution result is similar to the following:
系统架构: arm64
CPU 信息: [
{
model: 'Apple M1',
speed: 24,
times: { user: 18515240, nice: 0, sys: 9460280, idle: 38401220, irq: 0 }
}
...
]
空闲内存: 167411712
总内存: 8589934592
主目录: /Users/EXAMPLE
系统平台: darwin
系统名称: Darwin
平均负载: [ 11.4658203125, 4.49560546875, 3.35791015625 ]
网络接口信息: {
...
Other extensions
Node.js built-in modules