📗

Node.js SDK

v0.1.4

Official Node.js SDK for CronBeats ping telemetry. TypeScript-first with full type definitions and Promise-based async API.

Installation

Install via npm or yarn:

npm install @cronbeats/cronbeats-node
yarn add @cronbeats/cronbeats-node

Requirements: Node.js 14 or higher

Quick Start

Send a simple ping to mark your cron job as successful:

import { PingClient } from '@cronbeats/cronbeats-node';

const client = new PingClient('YCrXzYbV');
await client.ping();

// Done! CronBeats knows your job ran successfully.

Sending Pings

Simple Ping

Send a single heartbeat when your job completes:

const client = new PingClient('YCrXzYbV');
await client.ping();

Start & End Signals

Track execution time by signaling when your job starts and ends:

const client = new PingClient('YCrXzYbV');

await client.start();
// ... do your work ...
await client.success();  // or client.fail() on error

Real-World Cron Job Example

Complete example with error handling:

import { PingClient } from '@cronbeats/cronbeats-node';

const client = new PingClient('YCrXzYbV');
await client.start();

try {
    // Your actual cron job work
    await processEmails();
    await generateReports();
    await cleanupTempFiles();
    
    await client.success();
} catch (error) {
    await client.fail();
    console.error(error);
    process.exit(1);
}

Progress Tracking

Send real-time progress updates from long-running jobs. CronBeats displays a live progress bar and status message on your dashboard.

📊 Two Progress Modes

Mode 1: With Percentageclient.progress({seq: 50, message: "..."})

Dashboard shows progress bar (0-100%) + your message. Use when you can calculate meaningful progress.

Mode 2: Message Onlyclient.progress({message: "..."})

Dashboard shows only your status message (no percentage bar). Use for status updates without measurable progress.

Basic Progress Update

// Send progress percentage (0-100) with status message
await client.progress(50, 'Processing batch 50/100');

// Using object syntax
await client.progress({
    seq: 75,
    message: 'Almost done'
});

Processing Records Example

const client = new PingClient('YCrXzYbV');
await client.start();

const total = 10000;
for (let i = 1; i <= total; i++) {
    await processRecord(i);
    
    // Update progress every 500 records
    if (i % 500 === 0) {
        const percent = Math.floor(i * 100 / total);
        await client.progress(percent, `Processed ${i.toLocaleString()} / ${total.toLocaleString()} records`);
    }
}

await client.progress(100, 'All records processed');
await client.success();

Error Handling

The SDK throws typed errors for validation and API issues:

import { PingClient, ValidationError, ApiError } from '@cronbeats/cronbeats-node';

const client = new PingClient('YCrXzYbV');

try {
    await client.ping();
    
} catch (error) {
    if (error instanceof ValidationError) {
        // Invalid job key format or parameters (client-side)
        console.error('Validation error:', error.message);
        
    } else if (error instanceof ApiError) {
        // API/network issue with normalized metadata
        console.error('API error:', error.code);      // e.g. 'RATE_LIMITED'
        console.error('HTTP status:', error.httpStatus); // e.g. 429
        console.error('Retryable:', error.retryable);   // boolean
    }
}

TypeScript Support

The SDK is written in TypeScript with full type definitions included:

import { PingClient, PingClientOptions, ProgressOptions } from '@cronbeats/cronbeats-node';

const options: PingClientOptions = {
    baseUrl: 'https://cronbeats.io',
    timeoutMs: 5000,
    maxRetries: 2
};

const client = new PingClient('YCrXzYbV', options);

const progressOpts: ProgressOptions = {
    seq: 50,
    message: 'Half done'
};

await client.progress(progressOpts);

API Reference

Method Description
ping() Send a simple heartbeat ping
start() Signal job start and begin execution timer
end(status) Signal job end with status ("success" or "fail")
success() Alias for end("success")
fail() Alias for end("fail")
progress(seq, msg?) Send progress update (0-100) with optional status message

For complete API documentation, see the GitHub repository.

Configuration Options

Customize the client behavior:

const client = new PingClient('YCrXzYbV', {
    baseUrl: 'https://cronbeats.io',  // Default
    timeoutMs: 5000,                  // Default: 5 seconds
    maxRetries: 2                     // Default: 2 retries
});

Note: The default 5-second timeout ensures the SDK never blocks your cron job if CronBeats is unreachable. Adjust only if you need longer waits.

Complete Examples

Database Backup with Progress

import { PingClient } from '@cronbeats/cronbeats-node';
import { exec } from 'child_process';
import { promisify } from 'util';

const execAsync = promisify(exec);
const client = new PingClient('YCrXzYbV');

await client.start();

try {
    await client.progress(10, 'Starting backup...');
    
    // Dump database
    await execAsync('mysqldump -u user -ppassword mydb > backup.sql');
    await client.progress(40, 'Database dumped');
    
    // Compress
    await execAsync('gzip backup.sql');
    await client.progress(70, 'Compression complete');
    
    // Upload to S3
    await execAsync('aws s3 cp backup.sql.gz s3://my-bucket/');
    await client.progress(90, 'Uploaded to S3');
    
    await client.progress(100, 'Backup complete');
    await client.success();
    
} catch (error) {
    await client.fail();
    throw error;
}

Multi-Step Pipeline

const client = new PingClient('YCrXzYbV');
await client.start();

const stages = [
    { pct: 0, msg: 'Step 1/4: Extract data', fn: extractData },
    { pct: 25, msg: 'Step 2/4: Transform data', fn: transformData },
    { pct: 50, msg: 'Step 3/4: Load to database', fn: loadData },
    { pct: 75, msg: 'Step 4/4: Validate results', fn: validateResults }
];

for (const stage of stages) {
    await client.progress(stage.pct, stage.msg);
    await stage.fn();
}

await client.progress(100, 'Pipeline complete');
await client.success();

Ready to Get Started?

Install the SDK and start monitoring your Node.js cron jobs in minutes