How to monitor disk space in TypeScript using df

This post shows a minimal TypeScript class that checks the free disk space of a mountpoint by parsing the output of df -m. It returns a structured result with a status of ok, warning or error so it can be used directly in a monitoring loop.

DiskSpace.ts
import { execFile } from "node:child_process";
import { promisify } from "node:util";

const execFileAsync = promisify(execFile);

export type CheckStatus = "ok" | "warning" | "error";

export interface CheckResult {
    status: CheckStatus;
    msg: string;
    freeMegabytes?: number;
    percentUsed?: number;
}

/**
 * Check how much free space remains on a given mountpoint.
 */
export class DiskSpaceChecker {
    private readonly mountpoint: string;
    private readonly warningThresholdPercent: number;

    constructor(mountpoint: string = "/", warningThresholdPercent: number = 80) {
        this.mountpoint = mountpoint;
        this.warningThresholdPercent = warningThresholdPercent;
    }

    async check(): Promise<CheckResult> {
        let stdout: string;
        try {
            // execFile avoids a shell, so the mountpoint can't be used for injection
            ({ stdout } = await execFileAsync("df", ["-m", this.mountpoint]));
        } catch (error: any) {
            const code = error?.code;
            if (code === 1) {
                return { status: "error", msg: `No such mountpoint: ${this.mountpoint}` };
            }
            if (code === 127 || code === "ENOENT") {
                return { status: "error", msg: "df command not found" };
            }
            return { status: "error", msg: `df failed: ${error?.message ?? error}` };
        }

        const lines = stdout.trim().split("\n");
        if (lines.length < 2) {
            return { status: "error", msg: `Mountpoint not found: ${this.mountpoint}` };
        }

        // lines[1] example: /dev/sda1  122103  110897  9029  93% /
        const fields = lines[1].split(/\s+/);
        const freeMegabytes = Number.parseInt(fields[3], 10);
        const percentUsed = Number.parseInt(fields[4], 10);

        if (Number.isNaN(freeMegabytes) || Number.isNaN(percentUsed)) {
            return { status: "error", msg: `Could not parse df output: ${lines[1]}` };
        }

        return {
            status: percentUsed < this.warningThresholdPercent ? "ok" : "warning",
            msg: `Mount ${this.mountpoint}: ${freeMegabytes} MiB free, ${percentUsed}% used`,
            freeMegabytes,
            percentUsed,
        };
    }
}

Usage example

Call check() on a DiskSpaceChecker instance for the mountpoint you want to monitor. The promise always resolves with a CheckResult — errors such as a nonexistent mountpoint are reported as status: "error" instead of being thrown:

example.ts
import { DiskSpaceChecker } from "./DiskSpace.ts";

const checker = new DiskSpaceChecker("/"); // warning above 80% usage
const result = await checker.check();

console.log(result);
// {
//   status: 'warning',
//   msg: 'Mount /: 67897 MiB free, 93% used',
//   freeMegabytes: 67897,
//   percentUsed: 93
// }

To monitor periodically, just call it in a setInterval loop and react to the status field, e.g. send a notification when it is warning or error:

monitor.ts
import { DiskSpaceChecker } from "./DiskSpace.ts";

const checker = new DiskSpaceChecker("/data", 90); // warn above 90%

setInterval(async () => {
    const result = await checker.check();
    if (result.status !== "ok") {
        console.error(`Disk space ${result.status}: ${result.msg}`);
    }
}, 60_000); // check every minute

Since the code only uses erasable TypeScript syntax (types, but no enums or parameter properties), modern Node.js versions can run it directly without a build step:

run.sh
node --experimental-strip-types monitor.ts

On Node.js 23.6+ type stripping is enabled by default and the flag can be omitted.


Check out similar posts by category: TypeScript Linux