Grabrgrabr
Back to home

Library API

grabr can be imported programmatically into any Node.js or Bun project.

Installation

bash
bun add @linuxctrl/grabr

Import

typescript
import { Downloader, SpeedMeter, loadConfig, saveConfig } from "@linuxctrl/grabr";
import type { DownloadJob, DownloadOptions, JobStatus, ChunkInfo, GrabrConfig } from "@linuxctrl/grabr";

Downloader

The main class that orchestrates parallel chunked downloads. Extends EventEmitter.

Constructor

typescript
const downloader = new Downloader();
await downloader.start();

Methods

start(): Promise<void>

Initializes the downloader, loads interrupted jobs from the database, and starts the stats updater.

stop(): void

Stops all active downloads and clears the interval timer.

addJob(url: string, options?: DownloadOptions): Promise<DownloadJob>

Add a download job to the queue. Returns the created job.

typescript
const job = await downloader.addJob("https://example.com/file.zip", {
  outputDir: "./downloads",
  chunks: 4,
  filename: "myfile.zip",
});

pauseJob(jobId: string): Promise<void>

Pause a specific download job.

resumeJob(jobId: string): Promise<void>

Resume a paused or failed download job.

removeJob(jobId: string): Promise<void>

Remove a job from the queue and delete its resume state.

pauseAll(): Promise<void>

Pause all active and queued downloads.

resumeAll(): Promise<void>

Resume all paused and failed downloads.

Events

typescript
downloader.on("job:added", (job: DownloadJob) => {
  console.log("New job:", job.id);
});


downloader.on("job:progress", (data) => {
  console.log(`${data.jobId}: ${data.downloadedBytes} bytes`);
});


downloader.on("job:status", (data) => {
  console.log(`${data.jobId}: ${data.status}`);
});


downloader.on("job:removed", (jobId: string) => {
  console.log("Removed:", jobId);
});

Types

DownloadJob

typescript
interface DownloadJob {
  id: string;
  url: string;
  filename: string;
  destination: string;
  totalBytes: number;
  downloadedBytes: number;
  chunks: ChunkInfo[];
  status: "queued" | "downloading" | "paused" | "completed" | "failed";
  speed: number;
  eta: number;
  createdAt: number;
  updatedAt: number;
  error?: string;
}

ChunkInfo

typescript
interface ChunkInfo {
  index: number;
  start: number;
  end: number;
  downloaded: number;
  status: "pending" | "downloading" | "done" | "failed";
}

DownloadOptions

typescript
interface DownloadOptions {
  outputDir?: string;
  filename?: string;
  chunks?: number;
}

Config

typescript
import { loadConfig, saveConfig } from "@linuxctrl/grabr";


const config = loadConfig();
console.log(config.outputDir);


saveConfig({ defaultChunks: 8 });

Config is stored in ~/.grabr/config.json.

SpeedMeter

Utility class for EMA-smoothed speed calculation.

typescript
const meter = new SpeedMeter();
const speed = meter.update(1024);