get system free disk space in typescript

To get the free disk space of the system in TypeScript, we can use the fs (File System) module and the os (Operating System) module from Node.js. We first need to import these modules:

index.ts
import * as fs from 'fs';
import * as os from 'os';
52 chars
3 lines

Then we can use the fs.stat method to get file system information about the root directory (/) and calculate the free space by subtracting the used space from the total space. Here's the code:

index.ts
const root = '/';
const stats = fs.statSync(root);
const totalSpace = stats.blocks * stats.blksize;
const usedSpace = stats.blocks - stats.blocksFree;
const freeSpace = totalSpace - usedSpace;

console.log(`Total disk space: ${totalSpace} bytes`);
console.log(`Used disk space: ${usedSpace} bytes`);
console.log(`Free disk space: ${freeSpace} bytes`);
352 chars
10 lines

The blksize property represents the block size of the file system in bytes, and the blocks property represents the number of 512-byte blocks allocated to the file system. The blocksFree property represents the number of free blocks in the file system.

Note that this code will only work on Unix-based systems (including macOS and Linux). On Windows, you can use the win-disk-info library or the GetDiskFreeSpaceEx WinAPI function.

gistlibby LogSnag