One of the powerful aspects of Electron is its ability to interact with the underlying operating system. This goes beyond just file manipulation; you can glean valuable information about the user's system, which can be incredibly useful for customizing your application's behavior, providing better user experiences, or even for debugging purposes. In this section, we'll explore how to access common system information using Electron's built-in modules.
The primary module for accessing system information is the os module, which is a built-in Node.js module available directly within your Electron application. This module provides a wealth of information about the operating system, including CPU details, memory usage, network interfaces, and more.
const os = require('os');
console.log('Platform:', os.platform());
console.log('Architecture:', os.arch());
console.log('Total Memory:', os.totalmem(), 'bytes');
console.log('Free Memory:', os.freemem(), 'bytes');
console.log('CPU Info:', os.cpus());
console.log('Hostname:', os.hostname());Let's break down some of the useful methods from the os module:
os.platform(): Returns the operating system platform (e.g., 'darwin' for macOS, 'win32' for Windows, 'linux' for Linux).os.arch(): Returns the CPU architecture (e.g., 'x64', 'arm64').os.totalmem(): Returns the total amount of system memory in bytes.os.freemem(): Returns the number of free system memory in bytes.os.cpus(): Returns an array containing information about each CPU core, including its model, speed, and times.os.hostname(): Returns the network name of the computer.
Beyond the general os module, Electron also provides the process object, which is available globally in Node.js and thus in your Electron main process. This object offers information about the current Node.js process, including its environment and arguments.
console.log('Node.js Version:', process.version);
console.log('Process ID:', process.pid);
console.log('User Directory:', process.env.USERPROFILE || process.env.HOME);
console.log('Environment Variables:', process.env);Key properties of the process object include:
process.version: The Node.js version being used.process.pid: The process ID of the current Electron application.process.env: An object containing the user environment.process.argv: An array containing the command-line arguments passed to the Node.js process.