CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-cron-parser

Node.js library for parsing crontab instructions with timezone support, DST handling, and iterator capabilities

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

Cron Parser

A comprehensive JavaScript/TypeScript library for parsing and manipulating cron expressions. Features timezone support, DST (Daylight Saving Time) handling, iterator capabilities, and extended cron syntax including special characters like L (last day), # (nth occurrence), and H (hash/random).

Package Information

  • Package Name: cron-parser
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install cron-parser

Core Imports

import { CronExpressionParser } from "cron-parser";

For named imports:

import { 
  CronExpressionParser, 
  CronExpression, 
  CronDate, 
  CronFileParser 
} from "cron-parser";

For CommonJS:

const { CronExpressionParser, CronExpression, CronDate } = require("cron-parser");

Basic Usage

import { CronExpressionParser } from "cron-parser";

try {
  // Parse a cron expression
  const interval = CronExpressionParser.parse('*/2 * * * *');
  
  // Get next execution time
  console.log('Next:', interval.next().toString());
  
  // Get next 3 execution times
  console.log('Next 3:', interval.take(3).map(date => date.toString()));
  
  // Check if a specific date matches
  console.log('Matches now:', interval.includesDate(new Date()));
  
  // Convert back to cron string
  console.log('Expression:', interval.stringify());
} catch (err) {
  console.log('Error:', err.message);
}

Architecture

Cron Parser is built around several key components:

  • Expression Parser: CronExpressionParser class for parsing cron strings into structured objects
  • Expression Object: CronExpression class for iteration, validation, and date matching
  • Date Wrapper: CronDate class providing timezone-aware date operations with DST support
  • Field System: Individual field classes (CronSecond, CronMinute, etc.) with validation and constraints
  • File Parser: CronFileParser for parsing complete crontab files with variables and expressions
  • Special Syntax: Extended support for L (last), # (nth), H (hash/random), and predefined expressions

Capabilities

Expression Parsing

Core functionality for parsing cron expressions with extensive syntax support, validation, and configuration options.

class CronExpressionParser {
  static parse(expression: string, options?: CronExpressionOptions): CronExpression;
}

interface CronExpressionOptions {
  currentDate?: Date | string | number | CronDate;
  endDate?: Date | string | number | CronDate;
  startDate?: Date | string | number | CronDate;
  tz?: string;
  expression?: string;
  hashSeed?: string;
  strict?: boolean;
}

enum PredefinedExpressions {
  '@yearly' = '0 0 0 1 1 *',
  '@annually' = '0 0 0 1 1 *',
  '@monthly' = '0 0 0 1 * *',
  '@weekly' = '0 0 0 * * 0',
  '@daily' = '0 0 0 * * *',
  '@hourly' = '0 0 * * * *',
  '@minutely' = '0 * * * * *',
  '@secondly' = '* * * * * *',
  '@weekdays' = '0 0 0 * * 1-5',  
  '@weekends' = '0 0 0 * * 0,6'
}

Expression Parsing

Schedule Iteration

Iteration capabilities for finding next/previous execution times, checking date ranges, and iterating through scheduled times.

class CronExpression {
  next(): CronDate;
  prev(): CronDate;
  hasNext(): boolean;
  hasPrev(): boolean;
  take(limit: number): CronDate[];
  reset(newDate?: Date | CronDate): void;
  includesDate(date: Date | CronDate): boolean;
  [Symbol.iterator](): Iterator<CronDate>;
}

Schedule Iteration

Date Operations

Timezone-aware date operations with automatic DST handling and cron-specific functionality.

class CronDate {
  constructor(timestamp?: CronDate | Date | number | string, tz?: string);
  
  // Standard date methods
  getTime(): number;
  getFullYear(): number;
  getMonth(): number;
  getDate(): number;
  getDay(): number;
  getHours(): number;
  getMinutes(): number;
  getSeconds(): number;
  getMilliseconds(): number;
  
  // Date manipulation
  addYear(): void;
  addMonth(): void;
  addDay(): void;
  addHour(): void;
  addMinute(): void;
  addSecond(): void;
  
  // Cron-specific functionality
  isLastDayOfMonth(): boolean;
  isLastWeekdayOfMonth(): boolean;
}

enum TimeUnit {
  Second = 'Second',
  Minute = 'Minute', 
  Hour = 'Hour',
  Day = 'Day',
  Month = 'Month',
  Year = 'Year'
}

Date Operations

Field System

Individual cron field classes with validation, constraints, and special character support for building custom expressions.

class CronFieldCollection {
  constructor(fields: CronFields);
  
  readonly second: CronSecond;
  readonly minute: CronMinute;
  readonly hour: CronHour;
  readonly dayOfMonth: CronDayOfMonth;
  readonly month: CronMonth;
  readonly dayOfWeek: CronDayOfWeek;
  
  stringify(includeSeconds?: boolean): string;
  serialize(): SerializedCronFields;
}

interface CronFields {
  second: CronSecond;
  minute: CronMinute;
  hour: CronHour;
  dayOfMonth: CronDayOfMonth;
  month: CronMonth;
  dayOfWeek: CronDayOfWeek;
}

Field System

File Parsing

Parse complete crontab files with variable extraction, expression parsing, and error handling for system administration tasks.

class CronFileParser {
  static parseFile(filePath: string): Promise<CronFileParserResult>;
  static parseFileSync(filePath: string): CronFileParserResult;
}

interface CronFileParserResult {
  variables: { [key: string]: string };
  expressions: CronExpression[];
  errors: { [key: string]: unknown };
}

File Parsing

Types

// Range types for field values
type SixtyRange = 0 | 1 | 2 | ... | 59;  // 0-59 inclusive
type HourRange = 0 | 1 | 2 | ... | 23;   // 0-23 inclusive  
type DayOfMonthRange = 1 | 2 | 3 | ... | 31 | 'L';  // 1-31 inclusive + 'L'
type MonthRange = 1 | 2 | 3 | ... | 12;  // 1-12 inclusive
type DayOfWeekRange = 0 | 1 | 2 | ... | 7 | 'L';    // 0-7 inclusive + 'L'

// Special characters and constraints
type CronChars = 'L'; // 'W' is defined in types but not currently implemented
type CronMin = 0 | 1;
type CronMax = 7 | 12 | 23 | 31 | 59;

interface CronConstraints {
  min: CronMin;
  max: CronMax;
  chars: readonly CronChars[];
  validChars: RegExp;
}

// Field serialization
interface SerializedCronField {
  wildcard: boolean;
  values: (number | string)[];
}

interface SerializedCronFields {
  second: SerializedCronField;
  minute: SerializedCronField;
  hour: SerializedCronField;
  dayOfMonth: SerializedCronField;
  month: SerializedCronField;
  dayOfWeek: SerializedCronField;
}

Install with Tessl CLI

npx tessl i tessl/npm-cron-parser
Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/cron-parser@5.3.x
Publish Source
CLI
Badge
tessl/npm-cron-parser badge