How to check if a process is running in TypeScript using pgrep

pgrep exits with code 0 when at least one process matches the given name and code 1 when none does — which makes it a one-liner process liveness check. This post wraps it in a minimal TypeScript class returning a structured result.

Process.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;
}

/**
 * Check that at least one process with the given name is running, via pgrep.
 */
export class ProcessChecker {
    private readonly processName: string;

    constructor(processName: string = "nginx") {
        this.processName = processName;
    }

    async check(): Promise<CheckResult> {
        try {
            // Note: pgrep matches the pattern against the process name as a regex
            await execFileAsync("pgrep", [this.processName]);
            return { status: "ok", msg: `Process ${this.processName} is running` };
        } catch (error: any) {
            const code = error?.code;
            if (code === 1) {
                return { status: "error", msg: `No running ${this.processName} processes found` };
            }
            if (code === 127 || code === "ENOENT") {
                return { status: "error", msg: "pgrep command not found" };
            }
            return { status: "error", msg: `pgrep failed: ${error?.message ?? error}` };
        }
    }
}

Usage example

example.ts
import { ProcessChecker } from "./Process.ts";

console.log(await new ProcessChecker("sshd").check());
// { status: 'ok', msg: 'Process sshd is running' }

console.log(await new ProcessChecker("nosuchproc").check());
// { status: 'error', msg: 'No running nosuchproc processes found' }

Keep in mind that pgrep treats the argument as an extended regex matched against the process name, so ProcessChecker("node") also matches e.g. node-exporter. Pass -x in the execFileAsync arguments if you need an exact match — but note that -x compares against the 15-character comm name, which some runtimes rewrite.


Check out similar posts by category: TypeScript Linux Monitoring