Skip to main content
This guide will help you get up and running with the most popular Kreisler packages. Each example uses real code from the package source and tests.
Make sure you’ve installed the packages you want to use before following these examples.

Creating API clients

The @kreisler/createapi package provides a unique proxy-based approach to making HTTP requests without defining endpoints upfront.
1

Install the package

npm install @kreisler/createapi
2

Create an API client

Import and create your API client:
import { createApi } from '@kreisler/createapi'

// Create a client for any API
const api = createApi('https://api.adviceslip.com')
3

Make requests

Access endpoints dynamically through property access:
// GET https://api.adviceslip.com/advice
const response = await api.advice()
console.log(response.slip.advice)
// Output: "If you want to be happily married, marry a happy person."

Advanced API usage

// Pass query parameters as an object
const api = createApi('https://nekobot.xyz/api')
const output = await api.image({ type: 'neko' })
// Final URL: https://nekobot.xyz/api/image?type=neko
console.log(output)
// { success: true, message: "https://...", color: 13419230 }
Use x_response: true to get the raw Response object, or x_text: true to get text instead of JSON.

Error handling

The @kreisler/try-catch package provides functional error handling with TypeScript support.
import { tryCatch } from '@kreisler/try-catch'

// Handle errors from synchronous functions
const [error, result] = tryCatch(JSON.parse, '{"hello":"world"}')

if (error) {
  console.error('Parse failed:', error.message)
} else {
  console.log(result) // { hello: 'world' }
}
The error is always returned as the first element of the array. If there’s no error, it will be null.

Debouncing functions

The @kreisler/debounce package helps you control function execution timing with advanced features.
import { debounce } from '@kreisler/debounce'

// Basic debounce
const handleSearch = (query) => {
  console.log('Searching for:', query)
  // Make API call here
}

const debouncedSearch = debounce(handleSearch, 1000)

// These calls will be debounced
debouncedSearch('hello')     // Cancelled
debouncedSearch('hello wo')  // Cancelled
debouncedSearch('hello world') // Executes after 1 second

Advanced debounce features

import { debounce } from '@kreisler/debounce'

const handleInput = (value) => {
  console.log('Final value:', value)
}

const debouncedInput = debounce(handleInput, 1000, {
  // Execute immediately on first call
  immediate: true,
  
  // Called every time the debounced function is invoked
  onCall: (value) => {
    console.log('Input changed:', value)
  },
  
  // Called when debounce completes
  onComplete: (value) => {
    console.log('Debounce completed for:', value)
  },
  
  // Trigger flood handler after 7 calls
  flood: 7,
  
  // Called when flood limit is reached
  onFlood: (value) => {
    console.log('Too many calls! Last value:', value)
  }
})

debouncedInput('hello') // Executes immediately (immediate: true)

JavaScript helpers

The @kreisler/js-helpers package provides useful utility functions for common tasks.
import { normalize } from '@kreisler/js-helpers'

// Remove accents and special characters
const text = 'ÁÉÍÓÚáéíóú'
const normalized = normalize(text)
console.log(normalized) // 'AEIOUaeiou'

// For URLs (removes special chars and lowercases)
const url = normalize('Hello World! 2024', false)
console.log(url) // 'hello-world-2024'

Scheduled tasks

The @kreisler/js-cron package wraps node-cron with a clean class-based interface.
1

Initialize the scheduler

import { JsCron } from '@kreisler/js-cron'

const cron = new JsCron({ timezone: 'America/Bogota' })
2

Create a task

// Run every 10 seconds
const result = cron.createTask(
  'myTask',
  '*/10 * * * * *',
  () => {
    console.log('Task executed at', new Date())
  }
)

console.log(result)
// { success: true, message: 'Tarea "myTask" creada con éxito.', task: ... }
3

Control task execution

// Pause the task
cron.pauseTask('myTask')

// Resume the task
cron.resumeTask('myTask')

// Destroy the task
cron.destroyTask('myTask')

Cron expression examples

Every 15 minutes

'0 */15 * * * *'

Every hour at minute 0

'0 0 * * * *'

Business hours only

'0 */15 6-23 * * *'
// Every 15 minutes from 6 AM to 11 PM

Every weekday at 9 AM

'0 0 9 * * 1-5'

Execute shell commands

The @kreisler/exec-promise package wraps child_process.exec in a promise.
import { execPromise } from '@kreisler/exec-promise'

try {
  const { stdout, stderr } = await execPromise('echo %PATH%')
  console.log('Output:', stdout)
  
  if (stderr) {
    console.error('Errors:', stderr)
  }
} catch (error) {
  console.error('Command failed:', error.message)
}

Real-world example

import { execPromise } from '@kreisler/exec-promise'
import { tryCatchPromise } from '@kreisler/try-catch'

// Combine with error handling
const [error, result] = await tryCatchPromise(
  execPromise,
  'git status --short'
)

if (error) {
  console.error('Git command failed:', error.message)
} else {
  console.log('Changed files:', result.stdout)
}

ESM dirname

The @kreisler/dirname-for-module package provides __dirname functionality for ES modules.
import { __dirname } from '@kreisler/dirname-for-module'
import { join } from 'path'

// Use __dirname in ES modules
const configPath = join(__dirname, 'config.json')
console.log('Config file:', configPath)

// Works with both npm and pnpm installations
This package automatically detects whether you’re using npm or pnpm and adjusts the path calculation accordingly.

Combining packages

Kreisler packages work well together. Here’s an example combining multiple packages:
import { createApi } from '@kreisler/createapi'
import { tryCatchPromise } from '@kreisler/try-catch'
import { debounce } from '@kreisler/debounce'
import { normalize } from '@kreisler/js-helpers'

// Create a debounced search function with error handling
const api = createApi('https://api.example.com')

const searchUser = async (query) => {
  const normalizedQuery = normalize(query, false)
  const [error, result] = await tryCatchPromise(
    api.users,
    { q: normalizedQuery }
  )
  
  if (error) {
    console.error('Search failed:', error.message)
    return []
  }
  
  return result.data
}

const debouncedSearch = debounce(searchUser, 500, {
  onCall: () => console.log('Searching...'),
  onComplete: () => console.log('Search complete')
})

// Use it in your application
debouncedSearch('Jóhn Döe')

TypeScript support

All packages include TypeScript definitions. Here’s how to use them:
import { createApi, type ArgsCreateApi } from '@kreisler/createapi'
import { tryCatchPromise } from '@kreisler/try-catch'
import { JsCron, type ScheduleOptions } from '@kreisler/js-cron'

// Type-safe API interface
interface MyAPI {
  users: (params: { q: string }) => Promise<{ data: User[] }>
}

interface User {
  id: number
  name: string
  email: string
}

const api = createApi<MyAPI>('https://api.example.com')

// TypeScript will infer types correctly
const [error, result] = await tryCatchPromise(
  api.users,
  { q: 'john' }
)

if (!error && result) {
  result.data.forEach((user: User) => {
    console.log(user.name)
  })
}

Next steps

Core utilities

Explore API client, debounce, error handling utilities

API reference

View complete API documentation

Helpers & tools

String manipulation, conversions, and more

GitHub

Contribute to the project

Build docs developers (and LLMs) love