Kévin Bobo
Kévin Bobo

Reputation: 61

How do I calculate free disk space on Linux in JavaScript?

I want calculate and display the free space of the home filesystem but there are 3-4 users, and all should be in javascript, how can we do ?

I know in linux shell , we can do :

df -h

But in javascript it's not

Upvotes: 5

Views: 26628

Answers (6)

JozefS
JozefS

Reputation: 448

NodeJS, in v19.6, added support for statfs and statfsSync.

import { statfs } from 'fs';

// path in mounted volume
const pathToCheck = '/';

const space = statfs(pathToCheck, (err, stats) => {
  if (err) {
    throw err
  }
  console.log('Total free space',stats.bsize*stats.bfree);
  console.log('Available for user',stats.bsize*stats.bavail);
})

Upvotes: 9

mikemaccana
mikemaccana

Reputation: 123248

Node diskusage will do this. Please refer to the diskusage docs for more information about the package:

import { check } from "diskusage";

const log = console.log.bind(console);

async function getFreeSpace(path) {
  const diskUsage = await check(path);
  log(`Disk space available to the current user: ${diskUsage.free}`);
  log(`Disk space physically free: ${diskUsage.free}`);
  log(`Total disk space (free + used): ${diskUsage.free}`);
}

getFreeSpace("/home/mike");

Upvotes: 6

shreyasm-dev
shreyasm-dev

Reputation: 2834

You can do it by running the command df -h > df.txt which writes the df -h output to a file named df.txt. Then you could read the file and match a regex to it.

const { execSync } = require('child_process');
const { readFileSync, unlinkSync } = require('fs')

var space;

execSync('df -h > df.txt');

space = readFileSync('df.txt', (data, err) => {
  if (err) {
    throw err
  }
}).toString().match(/[0-9]+\.[0-9]+?../)[0]

console.log(space)

Upvotes: 0

Mohammad Ebrahimi
Mohammad Ebrahimi

Reputation: 57

You can either use diskusage npm and child_process.exec('df / -h') to get this parameter. but diskusage npm is more reliable and easy to use. if you use cp.exec('...') you should process the returned string by yourself to retrieve the desired parameters.

Upvotes: 0

venksster
venksster

Reputation: 73

shameless plug - https://www.npmjs.com/package/microstats

Can also be configured to alert the user when disk space crosses user defined threshold. works for linux, macOS and windows.

Upvotes: 1

NMunro
NMunro

Reputation: 910

What JavaScript environment are you using? NodeJS has a childprocess module that you can use to spawn a df command, see http://nodejs.org/api/child_process.html for more details.

I imagine that you're not attempting this in a browser based JavaScript sandbox.

Upvotes: 1

Related Questions