jchook / rewait

Wait for resources to become available -- http, https, tcp, sockets, files, and custom functions.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Rewait

Node JS library to await promises, then retry or timeout.

  • files
  • sockets
  • http/https
  • custom functions

Example

const { retry, http, socket } = require('rewait')

retry(
  [
    http('http://localhost:3000'),
    http('https://localhost:3001/path/to/thing.txt'),
    socket('/var/run/app.sock'),
  ],
  {
    interval: 500, // check (at most) every 1/2 second
    timeout: 60000, // timeout after 60 seconds (on the dot)
  }
).then(() => {
  console.log('Ready!')
})

Usage

retry(fns, [options])

Retry the given functions until they all resolve, or timeout.

It will not retry a given function until the returned promise resolves.

  • fns: Array<Function> | Function
  • options: Object | undefined
    • interval: Number (default: 250)
    • timeout: Number (default: Infinity)
    • verbose: Boolean (default: false)

http(url, [options])

Check for a 2XX or 3XX response from an HTTP or HTTPS endpoint.

The bail parameter abandons the request as soon as it receives data.

socket(str, [options])

Check a TCP or UNIX socket connection.

If you pass a string for str, it can take either the form host:port or /path/to/socket

file(path, [options])

Check a file.

You can easily verify the file using the checkOk option. For example, to check if the file is writable...

file('/path/to/file.txt', {
  checkOk: stats => stats.isFile() && stats.mode & 0700,
})
  • path: string
  • options: Object | null

Custom function

Simply throw an Error when "not ready".

Example:

function customCheck(options = {}) {
  return async () => {
    if (options.neverReady) {
      throw new Error('Never ready!')
    }
    if (options.waitUntil) {
      if (+new Date() < options.waitUntil) {
        throw new Error('Not ready!')
      }
    }
    // Ready, simply by not throwing
  }
}

About

Wait for resources to become available -- http, https, tcp, sockets, files, and custom functions.


Languages

Language:JavaScript 100.0%