{"id":13012,"library":"cron-parser","title":"Cron Expression Parser","description":"cron-parser is a robust Node.js library for parsing, validating, and iterating over cron expressions. It currently stands at stable version 5.5.0 and demonstrates a consistent release cadence with frequent updates addressing bug fixes, performance improvements, and new features like the `H` (hashed value) syntax. Key differentiators include comprehensive timezone support, intelligent handling of Daylight Saving Time (DST), and an iterator-based API for easily generating future schedule dates. It supports both standard cron formats and several special characters like `L` (last day), `#` (nth day of week), and `H` (randomized values), alongside predefined expressions such as `@daily` and `@hourly`. The library is ESM-first and requires Node.js >= 18 and TypeScript >= 5.","status":"active","version":"5.5.0","language":"javascript","source_language":"en","source_url":"https://github.com/harrisiirak/cron-parser","tags":["javascript","cron","crontab","parser","typescript"],"install":[{"cmd":"npm install cron-parser","lang":"bash","label":"npm"},{"cmd":"yarn add cron-parser","lang":"bash","label":"yarn"},{"cmd":"pnpm add cron-parser","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Internal dependency for date/time manipulation and timezone handling.","package":"luxon","optional":false}],"imports":[{"note":"The library is primarily designed for ES Modules. While CommonJS `require` might work in some setups, native ESM import is the recommended approach for Node.js >= 18.","wrong":"const { parseExpression } = require('cron-parser');","symbol":"parseExpression","correct":"import { parseExpression } from 'cron-parser';"},{"note":"CronExpression is a named export, not a default export.","wrong":"import CronExpression from 'cron-parser';","symbol":"CronExpression","correct":"import { CronExpression } from 'cron-parser';"},{"note":"Importing types requires the `type` keyword in TypeScript for clarity and to prevent bundling issues, especially in mixed ESM/CJS environments.","symbol":"CronOptions","correct":"import type { CronOptions } from 'cron-parser';"}],"quickstart":{"code":"import { parseExpression, CronExpression } from 'cron-parser';\n\nasync function getNextScheduledTimes(cronExpression: string, count: number = 5): Promise<Date[]> {\n  try {\n    const options: CronOptions = {\n      currentDate: new Date(),\n      tz: 'America/New_York', // Specify a timezone, e.g., process.env.TZ ?? 'UTC'\n      iterator: true\n    };\n    const interval: CronExpression = parseExpression(cronExpression, options);\n    const nextDates: Date[] = [];\n\n    for (let i = 0; i < count; i++) {\n      try {\n        const next = interval.next();\n        nextDates.push(next.value.toDate());\n      } catch (e) {\n        console.warn(`Could not get next date ${i + 1}:`, (e as Error).message);\n        break;\n      }\n    }\n    return nextDates;\n  } catch (err) {\n    console.error(`Error parsing cron expression '${cronExpression}':`, (err as Error).message);\n    return [];\n  }\n}\n\n// Example usage: Every minute, between 9 AM and 5 PM, Monday to Friday in New York\nconst cronString = '0 */1 9-17 * * 1-5'; \n\ngetNextScheduledTimes(cronString, 3).then(dates => {\n  console.log(`Next 3 occurrences for '${cronString}':`);\n  dates.forEach(date => console.log(date.toISOString()));\n});\n\n// Example with predefined expression\ngetNextScheduledTimes('@daily', 2).then(dates => {\n  console.log(`\\nNext 2 occurrences for '@daily':`);\n  dates.forEach(date => console.log(date.toISOString()));\n});","lang":"typescript","description":"This quickstart demonstrates how to parse a cron expression, specify timezone options, and iterate through the next scheduled dates using the `parseExpression` function and `CronExpression` iterator."},"warnings":[{"fix":"Review the pull request #379 for detailed changes. If directly constructing `CronField` objects, adapt to the new constructor signature. If using `nthDayOfWeek` in options, find an alternative approach or ensure your cron expression implicitly handles it.","message":"The `CronField` constructor signature changed and the `nthDayOfWeek` field was removed from `CronExpressionOptions`. This impacts direct manipulation of cron field objects.","severity":"breaking","affected_versions":">=5.2.0"},{"fix":"For versions before 5.0.5, always explicitly specify the `tz` option in `CronOptions` if you need a specific timezone, or update to v5.0.5 or later to use the system's local timezone by default for `currentDate`.","message":"Prior to v5.0.5, `cron-parser` would set the `currentDate` to UTC by default if no timezone was specified, which could lead to unexpected results when running in a local timezone. This was reverted to use the current system timezone.","severity":"gotcha","affected_versions":"<5.0.5"},{"fix":"Ensure you are using `cron-parser` version 5.1.1 or newer to benefit from the fix for last day of month handling when an explicit month is set.","message":"When using the `L` (last day of month) special character, specific issues with handling explicit months have been fixed in v5.1.1. Incorrect dates could be returned for certain last-day scenarios.","severity":"gotcha","affected_versions":"<5.1.1"},{"fix":"Update to version 5.3.1 or newer to ensure correct validation and parsing of cron expressions involving start and end date spans.","message":"Invalid start and end time span validation logic issues existed in versions prior to 5.3.1, potentially leading to incorrect range parsing or unexpected errors when defining expression spans.","severity":"gotcha","affected_versions":"<5.3.1"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Double-check the cron expression against the documentation for valid fields, ranges, and special characters. Ensure all required fields (minute, hour, day of month, month, day of week, and optional second) are present and correctly formatted.","cause":"The provided cron string does not conform to the expected format or contains invalid characters/ranges.","error":"Error: Not a valid CRON expression"},{"fix":"Change `const { parseExpression } = require('cron-parser');` to `import { parseExpression } from 'cron-parser';`. Ensure your environment supports ES Modules or transpile your code if necessary.","cause":"Attempting to use CommonJS `require()` syntax in an ES Module context (`type: 'module'` in package.json or `.mjs` file).","error":"TypeError: require is not defined in ES module scope"},{"fix":"Run `npm install cron-parser` or `yarn add cron-parser`. For TypeScript, ensure `esModuleInterop` is `true` in your `tsconfig.json` if encountering issues with default/named imports, though `cron-parser` provides types.","cause":"The `cron-parser` package is not installed or not correctly recognized by your module resolution system (e.g., TypeScript or Node.js).","error":"Error: Cannot find module 'cron-parser' or its corresponding type declarations."}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":null,"cli_name":""}