The os module in Node.js provides a way of interacting with the operating system. It offers various methods and properties to retrieve information about the underlying operating system, such as CPU architecture, network interfaces, memory usage, and more. This tutorial will guide you through using the os module to access these details.
The os module is part of Node.js's core modules, which means it is always available without needing to install any additional packages. It provides a set of functions that allow developers to interact with the operating system in a cross-platform manner. This makes it easier to write code that can run on different operating systems like Windows, macOS, and Linux.
The os.platform() method returns a string identifying the operating system platform for which the Node.js binary was compiled. Possible values are 'aix', 'darwin', 'freebsd', 'linux', 'openbsd', 'sunos', and 'win32'.
1const os = require('os');23console.log(os.platform());
$ node app.js
linux
The os.arch() method returns a string identifying the operating system CPU architecture for which the Node.js binary was compiled. Possible values are 'arm', 'arm64', 'ia32', 'mips', 'mipsel', 'ppc', 'ppc64', 's390', 's390x', and 'x64'.
1const os = require('os');23console.log(os.arch());
$ node app.js
x64
The os.totalmem() method returns the total amount of system memory in bytes as an integer.
1const os = require('os');23console.log(os.totalmem());
$ node app.js
17179869184
The os.freemem() method returns the amount of free system memory in bytes as an integer.
1const os = require('os');23console.log(os.freemem());
$ node app.js
8589934592
The os.hostname() method returns the hostname of the operating system as a string.
1const os = require('os');23console.log(os.hostname());
$ node app.js
my-hostname.local
The os.networkInterfaces() method returns an object containing network interfaces that have been assigned a network address.
1const os = require('os');23console.log(os.networkInterfaces());
$ node app.js
{
lo0: [
{
address: '127.0.0.1',
netmask: '255.0.0.0',
family: 'IPv4',
mac: '00:00:00:00:00:00',
internal: true,
cidr: '127.0.0.1/8'
}
],
en0: [
{
address: '192.168.1.100',
netmask: '255.255.255.0',
family: 'IPv4',
mac: 'a0:b3:c3:d4:e5:f6',
internal: false,
cidr: '192.168.1.100/24'
}
]
}In the next section, we will explore how to manage child processes in Node.js using the child_process module.
Info
Remember, the os module is a powerful tool for accessing system-level information. It can be particularly useful for applications that need to adapt their behavior based on the underlying operating system.