Skip to main content

Node.js SDK

The Node.js SDK for writing TaskDaemon handlers.

Installation

npm install @taskdaemon/handler

Basic Usage

import { run, success, error, Task } from '@taskdaemon/handler';

function handler(task: Task) {
  const name = task.task_data.name || 'World';
  return success({ message: `Hello, ${name}!` });
}

run(handler);

Task Interface

interface Task {
  task_id: string;
  task_type: string;
  task_data: Record<string, unknown>;
  attempt: number;  // Current attempt (starts at 0)
}

Return Types

The SDK provides helper functions for creating results:
// Success with result
return success({ processed: true, count: 42 });

// Non-retryable error (default)
return error("Invalid input");

// Retryable error
return error("Service unavailable", true);
Or construct the result object directly:
type Result =
  | { status: 'success'; result: unknown }
  | { status: 'error'; error: string; retryable: boolean };

Async Handlers

Handlers can be async:
import { run, success, error, Task } from '@taskdaemon/handler';
import axios from 'axios';

async function handler(task: Task) {
  try {
    const response = await axios.get(task.task_data.url as string);
    return success({ data: response.data });
  } catch (e) {
    return error(String(e), true);  // Retryable
  }
}

run(handler);

Complete Example

import { run, success, error, Task } from '@taskdaemon/handler';
import sharp from 'sharp';
import axios from 'axios';

async function resizeImage(task: Task) {
  try {
    const { image_url, width, height } = task.task_data as {
      image_url: string;
      width: number;
      height: number;
    };
    
    // Download image
    const response = await axios.get(image_url, { responseType: 'arraybuffer' });
    
    // Resize
    const resized = await sharp(response.data)
      .resize(width, height)
      .png()
      .toBuffer();
    
    // Encode
    const b64 = resized.toString('base64');
    
    return success({ 
      data: b64, 
      size: [width, height],
      format: 'png'
    });
  } catch (e) {
    return error(String(e));
  }
}

run(resizeImage);

Error Handling

Uncaught exceptions are automatically converted to non-retryable errors:
function handler(task: Task) {
  // If this throws, it becomes { status: 'error', error: '...', retryable: false }
  const value = task.task_data.required_field;
  return success({ value });
}

Dockerfile

FROM node:20-slim

WORKDIR /app
COPY package*.json ./
RUN npm install

COPY handler.ts ./
RUN npx tsc handler.ts

CMD ["node", "handler.js"]
Or for JavaScript:
FROM node:20-slim

WORKDIR /app
COPY package*.json ./
RUN npm install

COPY handler.js ./

CMD ["node", "handler.js"]

Handler Configuration

[handlers.process]
image = "node-handler:latest"
instances = 4
timeout = 30