{"id":20522803,"url":"https://github.com/cronitorio/cronitor-js","last_synced_at":"2025-10-26T16:12:33.514Z","repository":{"id":41965787,"uuid":"49573160","full_name":"cronitorio/cronitor-js","owner":"cronitorio","description":"Cronitor Node Library","archived":false,"fork":false,"pushed_at":"2024-09-04T21:01:23.000Z","size":339,"stargazers_count":29,"open_issues_count":3,"forks_count":11,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-02-26T15:09:37.339Z","etag":null,"topics":["cronitor","cronjob","daemon","monitors","telemetry-pings","worker"],"latest_commit_sha":null,"homepage":"https://cronitor.io","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/cronitorio.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2016-01-13T12:45:05.000Z","updated_at":"2024-12-10T06:29:58.000Z","dependencies_parsed_at":"2024-01-17T21:35:47.472Z","dependency_job_id":"1c211faa-d56c-471f-ae0a-a321f239fab8","html_url":"https://github.com/cronitorio/cronitor-js","commit_stats":{"total_commits":76,"total_committers":5,"mean_commits":15.2,"dds":"0.48684210526315785","last_synced_commit":"4d025668b2fb05efece17979c4aa56ec3715b758"},"previous_names":["bigethan/cronitor-caller"],"tags_count":20,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cronitorio%2Fcronitor-js","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cronitorio%2Fcronitor-js/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cronitorio%2Fcronitor-js/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cronitorio%2Fcronitor-js/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/cronitorio","download_url":"https://codeload.github.com/cronitorio/cronitor-js/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":241950145,"owners_count":20047591,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cronitor","cronjob","daemon","monitors","telemetry-pings","worker"],"created_at":"2024-11-15T22:36:55.657Z","updated_at":"2025-10-26T16:12:33.501Z","avatar_url":"https://github.com/cronitorio.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Cronitor Javascript Library\n\n![Tests](https://github.com/cronitorio/cronitor-js/workflows/Node.js%20CI/badge.svg)\n\n[Cronitor](https://cronitor.io) provides end-to-end monitoring for background jobs, websites, APIs, and anything else that can send or receive an HTTP request. This library provides convenient access to the Cronitor API from applications written in Javascript. See our [API docs](https://cronitor.io/docs/api) for detailed references on configuring monitors and sending telemetry pings.\n\nIn this guide:\n\n- [Installation](#Installation)\n- [Monitoring Background Jobs](#monitoring-background-jobs)\n- [Sending Telemetry Events](#sending-telemetry-events)\n- [Configuring Monitors](#configuring-monitors)\n- [Package Configuration \u0026 Env Vars](#package-configuration)\n\n\n## Installation\n```\nnpm install cronitor --save\n# or\nyarn add cronitor\n```\n\n\n## Monitoring Background Jobs\n\n### Integrate with Cron Libraries\nIf you are using a library like [node-cron](https://github.com/node-cron/node-cron) or [cron](https://github.com/kelektiv/node-cron), this package provides a lightweight wrapper to enable easy monitoring integration.\n\n```javascript\nconst cron = require('cronitor')('cronitor_api_key');\nconst nodeCron = require('node-cron');\n\ncron.wraps(nodeCron);\n\n// the first parameter is now the key that Cronitor will use\n// to send telemetry events when the jobs runs, completes or fails\ncron.schedule('SendWelcomeEmail', '*/5 * * * *', () =\u003e {\n    console.log('Sending welcome email to new sign ups every five minutes.');\n});\n```\n\n### Monitor Any Function\n\nCronitor can wrap any function with telemetry pings.\n\n```javascript\nconst cronitor = require('cronitor')('cronitor_api_key');\n\nlet asyncWorker = cronitor.wrap('background-worker', async () =\u003e {\n    // do some async work\n});\n\n// cronitor will track the start and end time and state (promise resolved or rejected).\nawait asyncWorker();\n```\n\n### Monitor long running processes\nIf you have a long running process (Control-Loop, Daemon, Worker, etc) you might not care about the lifecycle (start/end),\nand instead wish to record counts/error counts of these events instead. Use the `Event`\nobject to synchronously record loop ticks and asynchronously batch report these events to Cronitor.\nThe following example uses [sqs-consumer](https://github.com/bbc/sqs-consumer).\n\n```javascript\nconst cronitor = require('cronitor')('cronitor_api_key');\nconst { Consumer } = require('sqs-consumer');\n\nevent = new cronitor.Event('monitor-key');\n\nconst app = Consumer.create({\n  queueUrl: 'https://sqs.eu-west-1.amazonaws.com/account-id/queue-name',\n  pollingWaitTimeMs: 100, // duration to wait before repolling the queue (defaults to 0).\n  handleMessage: async (message) =\u003e {\n    // do some work with `message`\n  }\n});\n\n// Consumer is an event emitter and will emit one of the below events each time it is called.\n// a message was processed\napp.on('processed_message', () =\u003e {\n    // increment the tick counter, no other side effects.\n    event.tick();\n});\n\n // the queue is empty\napp.on('empty', () =\u003e {\n    // record a tick and also record that no message was processed\n    event.tick(0);\n});\n\n// an error occurred connectiong to SQS\napp.on('error', (err) =\u003e {\n    // .error is a special \"tick\" method for reporting error counts.\n    // Use it to tell Cronitor your program is still running, but encountering errors.\n    // Error rate alert thresholds are configurable.\n  event.error();\n});\noncon\napp.start();\n```\n\n## Sending Telemetry Events\n\nIf you want to send a heartbeat events, or want finer control over when/how [telemetry events](https://cronitor.io/docs/telemetry-api) are sent for your jobs, you can create a monitor instance and call the `.ping` method.\n\n```javascript\nconst monitor = new cronitor.Monitor('heartbeat-monitor');\n\n// send a heartbeat event\nmonitor.ping();\n\n// optional params can be passed as an object.\n// for a complete list see https://cronitor.io/docs/ping-api\nmonitor.ping({\n    state: 'run|complete|fail|ok', // run/complete|fail used to measure lifecycle of a job.\n    env: '', // the environment this is running in (development, staging, production)\n    message: '', // optional message that will be displayed in alerts as well as monitor activity panel on your dashboard.\n    metrics: {\n        duration: 100,\n        count: 4500,\n        error_count: 10\n    }\n});\n```\n\n## Configuring Monitors\n\n### Yaml Configuration File\nYou can configure all of your monitors using a single YAML file. This can be version controlled and synced to Cronitor as part of\na deployment or build process. For details on all of the attributes that can be set, see the [Monitor API](https://cronitor.io/docs/monitor-api) documentation.\n\n```javascript\nconst cronitor = require('cronitor')('apiKey123');\n\ncronitor.readConfig({path: './cronitor.yaml'}); // parse the yaml file of monitors\n\ncronitor.validateConfig({path: './cronitor.yaml'}); // send monitors to Cronitor for configuration validation\n\ncronitor.applyConfig({path: './cronitor.yaml'}); // sync the monitors from the config file to Cronitor\n\ncronitor.generateConfig({path: './cronitor.yaml'}); // generate a new config file from the Cronitor API\n\n```\n\nThe `cronitor.yaml` file includes three top level keys `jobs`, `checks`, `heartbeats`. You can configure monitors under each key by defining [monitors](https://cronitor.io/docs/monitor-api#attributes).\n\n```yaml\njobs:\n    nightly-database-backup:\n        schedule: 0 0 * * *\n        notify:\n            - devops-alert-pagerduty\n        assertions:\n            - metric.duration \u003c 5 minutes\n\n    send-welcome-email:\n        schedule: every 10 minutes\n        assertions:\n            - metric.count \u003e 0\n            - metric.duration \u003c 30 seconds\n\nchecks:\n    cronitor-homepage:\n        request:\n            url: https://cronitor.io\n            regions:\n                - us-east-1\n                - eu-central-1\n                - ap-northeast-1\n        assertions:\n            - response.code = 200\n            - response.time \u003c 2s\n\n    cronitor-ping-api:\n        request:\n            url: https://cronitor.link/ping\n        assertions:\n            - response.body contains ok\n            - response.time \u003c .25s\n\nheartbeats:\n    production-deploy:\n        notify:\n            alerts: ['deploys-slack']\n            events: true # send alert when the event occurs\n\n```\n\n#### Async Uploads\nIf you are working with large YAML files (300+ monitors), you may hit timeouts when trying to sync monitors in a single http request. This workload to be processed asynchronously by adding the key `async: true` to the config file. The request will immediately return a `batch_key`. If a `webhook_url` parameter is included, Cronitor will POST to that URL with the results of the background processing and will include the `batch_key` matching the one returned in the initial response.\n\n\n### Monitor.put\n\nYou can also create and update monitors by calling `Monitor.put`. For details on all of the attributes that can be set see the Monitor API [documentation)(https://cronitor.io/docs/monitor-api#attributes).\n\n```javascript\nconst cronitor = require('cronitor')('apiKey123');\n\nconst jobMonitor = await cronitor.Monitor.put({\n    type: 'job',\n    key: 'send-customer-invoices',\n    schedule: '0 0 * * *',\n    assertions: [\n        'metric.duration \u003c 5 min'\n    ],\n    notify: ['devops-alerts-slack']\n});\n\nconst uptimeMonitor = await cronitor.Monitor.put({\n    type: 'check',\n    key: 'Cronitor Homepage',\n    schedule: 'every 45 seconds',\n    request: {\n        url: 'https://cronitor.io'\n    },\n    assertions: [\n        'response.code = 200',\n        'response.time \u003c 600ms'\n    ]\n})\n```\n\n### Pause, Reset, Delete\n\n```javascript\nconst monitor = new cronitor.Monitor('heartbeat-monitor');\n\nmonitor.pause(24) // pause alerting for 24 hours\nmonitor.unpause() // alias for .pause(0)\nmonitor.ok() // reset to a passing state alias for monitor.ping({state: ok})\nmonitor.delete() // destroy the monitor\n```\n\n## Package Configuration\n\nThe package needs to be configured with your account's `API key`, which is available on the [account settings](https://cronitor.io/settings) page. You can also optionally specify an `api_version`, an `environment`, a request `timeout`, and a cronitor `region`.\n\nThese can also be supplied using the environment variables `CRONITOR_API_KEY`, `CRONITOR_API_VERSION`, `CRONITOR_ENVIRONMENT`, `CRONITOR_TIMEOUT`, `CRONITOR_REGION`.\n\n```javascript\nconst cronitor = require('cronitor')(\n    'cronitor_api_key',\n    {\n        apiVersion: '2020-10-01',\n        environment: 'staging',\n        timeout: 5000,\n        region: 'eu'\n    });\n```\n\n\n## Contributing\n\nPull requests and features are happily considered! By participating in this project you agree to abide by the [Code of Conduct](http://contributor-covenant.org/version/2/0).\n\n### To contribute\n\nFork, then clone the repo:\n\n    git clone git@github.com:your-username/cronitor-js.git\n\nSet up your machine:\n\n    npm install\n\nMake sure the tests pass:\n\n    npm test\n\nMake your change. Add tests for your change. Make the tests pass:\n\n    npm test\n\n\nPush to your fork and [submit a pull request]( https://github.com/cronitorio/cronitor-js/compare/)\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcronitorio%2Fcronitor-js","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fcronitorio%2Fcronitor-js","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcronitorio%2Fcronitor-js/lists"}