Node.js Checkenv Script with Axios

A small Node.js CLI that polls URLs with Axios and reports when a service becomes ready.

2 min read Updated

A small Node.js health-check utility: it polls a URL with Axios at an interval, retries a configurable number of times and reports whether the service became ready. The files below are the module, the CLI entry point and its package.json.

Health.mjs

javascript
import axios from 'axios';

export default {
  check(url, { interval = 5, retries = 3, timeout = 10 } = {}) {
    trace.info(`Checking URL ${url}\n`);

    return new Promise((resolve) => {
      axios.get(url, { timeout: timeout * 1000 })
        .then(({ status }) => {
          if (status < 400) {
            trace.infob(`URL ${url} is up (${status})\n`);
            
            resolve(true);
          } else if (retries--) {
            trace.infob(`URL ${url} down (${status})... Retrying (${retries}) in ${interval}s...\n`);
            setTimeout(() => this.check(url, { interval, retries, timeout }).then((resolve)).catch(resolve), interval * 1000);
          } else {
            trace.infob(`Unable to reach ${url} (${status})\n`);
            resolve(false);
          }
        })
        .catch(({ message }) => {
          if (retries--) {
            trace.error(`Error when reaching '${url}': ${message}. Retrying (${retries}) in ${interval}s...\n`);
            setTimeout(() => this.check(url, { interval, retries, timeout }).then((resolve)).catch(resolve), interval * 1000);
          } else {
            trace.error(`Error when reaching '${url}': ${message}\n`);
            resolve(false);
          }
        });
    });
  },
};

main.mjs

javascript
import commander from 'commander';
import Healh from './Healh.mjs';

const program = new commander.Command();

program.name('checkenv');
program.version('1.0.0');

program
  .requiredOption('-e, --url <url>', 'URL to check')
  .option('-t, --timeout <ms>', 'Timeout in ms', '30000')
  .action(async () => {
    const { url, timeout } = program.opts();

    await Healh.check(url, Number.parseInt(timeout));
  });

program.parse();

package.json

json
{
  "name": "checkenv",
  "version": "1.0.0",
  "description": "Checkenv script",
  "main": "main.mjs",
  "type": "module",
  "scripts": {},
  "author": "Sébastien Demanou <demsking@gmail.com>",
  "license": "MIT",
  "dependencies": {
    "axios": "^0.21.1",
    "commander": "^7.1.0"
  }
}

Search articles

Type to filter articles. Use the arrow keys to move through results and Enter to open one. Press Escape to close.