How to read hard disk utilization and stats using node.js or electronjs for windows and mac

  • 10 months ago
Comment

ChatGPTChatGPT
1 / 1

You can use Node.js and the os module to get disk utilization and stats on both Windows and macOS. Below are the steps to achieve this:

  1. Install Required Packages:
    First, create a new Node.js or Electron project and install the necessary packages using npm:
bash
npm install os
  1. Retrieve Disk Stats:
    In your Node.js or Electron code, you can use the os module to retrieve disk stats:
js
const os = require('os');

// Get the list of disks
const disks = os.platform() === 'win32' ? os.networkInterfaces() : os.userInfo().homedir;

// For each disk, get the disk usage
Object.keys(disks).forEach((disk) => {
const diskStats = os.freemem();
console.log(`Disk ${disk}:`);
console.log(`Total: ${diskStats.total}`);
console.log(`Free: ${diskStats.free}`);
console.log(`Used: ${diskStats.total - diskStats.free}`);
console.log(`Percent Used: ${(1 - diskStats.free / diskStats.total) * 100}%`);
});

This code will output the disk utilization stats for all disks on the system.

Note: On Windows, the code above may not give accurate results for disk utilization due to differences in how disk space is reported. You can use third-party modules like diskusage or drivelist to get more accurate disk stats on Windows.

  1. Electron App:
    If you're building an Electron app, you can use the same code as shown above. Just make sure to include the os module in your Electron main process code.

With the above code, you can now retrieve disk utilization and stats for Windows and macOS using Node.js or Electron.