linkinator

A super simple site crawler and broken link checker

README

🐿 linkinator


A super simple site crawler and broken link checker.

npm version Build Status codecov Known Vulnerabilities Code Style: Google semantic-release


Behold my latest inator! The linkinator provides an API and CLI for crawling websites and validating links.  It's got a ton of sweet features:

- 🔥 Easily perform scans on remote sites or local files
- 🔥 Scan any element that includes links, not just ``
- 🔥 Supports redirects, absolute links, relative links, all the things
- 🔥 Configure specific regex patterns to skip
- 🔥 Scan markdown files without transpilation

Installation


  1. ```sh
  2. npm install linkinator
  3. ```


Command Usage


You can use this as a library, or as a CLI.  Let's see the CLI!

  1. ```text
  2. $ linkinator LOCATIONS [ --arguments ]

  3.   Positional arguments

  4.     LOCATIONS
  5.       Required. Either the URLs or the paths on disk to check for broken links.
  6.       Supports multiple paths, and globs.

  7.   Flags

  8.     --concurrency
  9.           The number of connections to make simultaneously. Defaults to 100.

  10.     --config
  11.         Path to the config file to use. Looks for `linkinator.config.json` by default.

  12.     --directory-listing
  13.         Include an automatic directory index file when linking to a directory.
  14.         Defaults to 'false'.

  15.     --format, -f
  16.         Return the data in CSV or JSON format.

  17.     --help
  18.         Show this command.

  19.     --include, -i
  20.         List of urls in regexy form to include.  The opposite of --skip.

  21.     --markdown
  22.         Automatically parse and scan markdown if scanning from a location on disk.

  23.     --recurse, -r
  24.         Recursively follow links on the same root domain.

  25.     --retry,
  26.         Automatically retry requests that return HTTP 429 responses and include
  27.         a 'retry-after' header. Defaults to false.

  28.     --retry-errors,
  29.         Automatically retry requests that return 5xx or unknown response.

  30.     --retry-errors-count,
  31.         How many times should an error be retried?

  32.     --retry-errors-jitter,
  33.         Random jitter applied to error retry.

  34.     --server-root
  35.         When scanning a locally directory, customize the location on disk
  36.         where the server is started.  Defaults to the path passed in [LOCATION].

  37.     --skip, -s
  38.         List of urls in regexy form to not include in the check.

  39.     --timeout
  40.         Request timeout in ms.  Defaults to 0 (no timeout).

  41.     --url-rewrite-search
  42.         Pattern to search for in urls.  Must be used with --url-rewrite-replace.

  43.     --url-rewrite-replace
  44.         Expression used to replace search content.  Must be used with --url-rewrite-search.

  45.     --verbosity
  46.         Override the default verbosity for this command. Available options are
  47.         'debug', 'info', 'warning', 'error', and 'none'.  Defaults to 'warning'.
  48. ```

Command Examples


You can run a shallow scan of a website for busted links:

  1. ```sh
  2. npx linkinator https://jbeckwith.com
  3. ```

That was fun.  What about local files?  The linkinator will stand up a static web server for yinz:

  1. ```sh
  2. npx linkinator ./docs
  3. ```

But that only gets the top level of links.  Lets go deeper and do a full recursive scan!

  1. ```sh
  2. npx linkinator ./docs --recurse
  3. ```

Aw, snap.  I didn't want that to check those links.  Let's skip em:

  1. ```sh
  2. npx linkinator ./docs --skip www.googleapis.com
  3. ```

The --skip parameter will accept any regex! You can do more complex matching, or even tell it to only scan links with a given domain:

  1. ```sh
  2. linkinator http://jbeckwith.com --skip '^(?!http://jbeckwith.com)'
  3. ```

Maybe you're going to pipe the output to another program.  Use the --format option to get JSON or CSV!

  1. ```sh
  2. linkinator ./docs --format CSV
  3. ```

Let's make sure the README.md in our repo doesn't have any busted links:

  1. ```sh
  2. linkinator ./README.md --markdown
  3. ```

You know what, we better check all of the markdown files!

  1. ```sh
  2. linkinator "**/*.md" --markdown
  3. ```

Configuration file


You can pass options directly to the linkinator CLI, or you can define a config file.  By default, linkinator will look for a linkinator.config.json file in the current working directory.

All options are optional. It should look like this:

  1. ``` json
  2. {
  3.   "concurrency": 100,
  4.   "config": "string",
  5.   "recurse": true,
  6.   "skip": "www.googleapis.com",
  7.   "format": "json",
  8.   "silent": true,
  9.   "verbosity": "error",
  10.   "timeout": 0,
  11.   "markdown": true,
  12.   "serverRoot": "./",
  13.   "directoryListing": true,
  14.   "retry": true,
  15.   "retryErrors": true,
  16.   "retryErrorsCount": 3,
  17.   "retryErrorsJitter": 5,
  18.   "urlRewriteSearch": "/pattern/",
  19.   "urlRewriteReplace": "replacement",
  20. }
  21. ```

To load config settings outside the CWD, you can pass the --config flag to the linkinator CLI:

  1. ```sh
  2. linkinator --config /some/path/your-config.json
  3. ```

GitHub Actions


You can use linkinator as a GitHub Action as well, using JustinBeckwith/linkinator-action:

  1. ```yaml
  2. on:
  3.   push:
  4.     branches:
  5.       - main
  6.   pull_request:
  7. name: ci
  8. jobs:
  9.   linkinator:
  10.     runs-on: ubuntu-latest
  11.     steps:
  12.       - uses: actions/checkout@v2
  13.       - uses: JustinBeckwith/linkinator-action@v1
  14.         with:
  15.           paths: README.md
  16. ```

To see all options or to learn more, visit JustinBeckwith/linkinator-action.

API Usage


linkinator.check(options)


Asynchronous method that runs a site wide scan. Options come in the form of an object that includes:

- path (string|string[]) - A fully qualified path to the url to be scanned, or the path(s) to the directory on disk that contains files to be scanned. required.
- concurrency (number) -  The number of connections to make simultaneously. Defaults to 100.
- port (number) - When the path is provided as a local path on disk, the port on which to start the temporary web server.  Defaults to a random high range order port.
- recurse (boolean) - By default, all scans are shallow.  Only the top level links on the requested page will be scanned.  By setting recurse to true, the crawler will follow all links on the page, and continue scanning links on the same domain for as long as it can go. Results are cached, so no worries about loops.
- retry (boolean|RetryConfig) - Automatically retry requests that respond with an HTTP 429, and include a retry-after header.  The RetryConfig option is a placeholder for fine-grained controls to be implemented at a later time, and is only included here to signal forward-compatibility.
- serverRoot (string) - When scanning a locally directory, customize the location on disk
where the server is started.  Defaults to the path passed in path.
- timeout (number) - By default, requests made by linkinator do not time out (or follow the settings of the OS).  This option (in milliseconds) will fail requests after the configured amount of time.
- markdown (boolean) - Automatically parse and scan markdown if scanning from a location on disk.
- linksToSkip (array | function) - An array of regular expression strings that should be skipped, OR an async function that's called for each link with the link URL as its only argument. Return a Promise that resolves to true to skip the link or false to check it.
- directoryListing (boolean) - Automatically serve a static file listing page when serving a directory.  Defaults to false.
- urlRewriteExpressions (array) - Collection of objects that contain a search pattern, and replacement.

linkinator.LinkChecker()


Constructor method that can be used to create a new LinkChecker instance.  This is particularly useful if you want to receive events as the crawler crawls.  Exposes the following events:

- pagestart (string) - Provides the url that the crawler has just started to scan.
- link (object) - Provides an object with
  - url (string) - The url that was scanned
  - state (string) - The result of the scan.  Potential values include BROKEN, OK, or SKIPPED.
  - status (number) - The HTTP status code of the request.

Examples


Simple example


  1. ``` js
  2. const link = require('linkinator');

  3. async function simple() {
  4.   const results = await link.check({
  5.     path: 'http://example.com'
  6.   });

  7.   // To see if all the links passed, you can check `passed`
  8.   console.log(`Passed: ${results.passed}`);

  9.   // Show the list of scanned links and their results
  10.   console.log(results);

  11.   // Example output:
  12.   // {
  13.   //   passed: true,
  14.   //   links: [
  15.   //     {
  16.   //       url: 'http://example.com',
  17.   //       status: 200,
  18.   //       state: 'OK'
  19.   //     },
  20.   //     {
  21.   //       url: 'http://www.iana.org/domains/example',
  22.   //       status: 200,
  23.   //       state: 'OK'
  24.   //     }
  25.   //   ]
  26.   // }
  27. }
  28. simple();
  29. ```

Complete example


In most cases you're going to want to respond to events, as running the check command can kinda take a long time.

  1. ``` js
  2. const link = require('linkinator');

  3. async function complex() {
  4.   // create a new `LinkChecker` that we'll use to run the scan.
  5.   const checker = new link.LinkChecker();

  6.   // Respond to the beginning of a new page being scanned
  7.   checker.on('pagestart', url => {
  8.     console.log(`Scanning ${url}`);
  9.   });

  10.   // After a page is scanned, check out the results!
  11.   checker.on('link', result => {

  12.     // check the specific url that was scanned
  13.     console.log(`  ${result.url}`);

  14.     // How did the scan go?  Potential states are `BROKEN`, `OK`, and `SKIPPED`
  15.     console.log(`  ${result.state}`);

  16.     // What was the status code of the response?
  17.     console.log(`  ${result.status}`);

  18.     // What page linked here?
  19.     console.log(`  ${result.parent}`);
  20.   });

  21.   // Go ahead and start the scan! As events occur, we will see them above.
  22.   const result = await checker.check({
  23.     path: 'http://example.com',
  24.     // port: 8673,
  25.     // recurse: true,
  26.     // linksToSkip: [
  27.     //   'https://jbeckwith.com/some/link',
  28.     //   'http://example.com'
  29.     // ]
  30.   });

  31.   // Check to see if the scan passed!
  32.   console.log(result.passed ? 'PASSED :D' : 'FAILED :(');

  33.   // How many links did we scan?
  34.   console.log(`Scanned total of ${result.links.length} links!`);

  35.   // The final result will contain the list of checked links, and the pass/fail
  36.   const brokeLinksCount = result.links.filter(x => x.state === 'BROKEN');
  37.   console.log(`Detected ${brokeLinksCount.length} broken links.`);
  38. }

  39. complex();
  40. ```

Tips & Tricks


Using a proxy


This library supports proxies via the HTTP_PROXY and HTTPS_PROXY environment variables.  This guide provides a nice overview of how to format and set these variables.

Globbing


You may have noticed in the example, when using a glob the pattern is encapsulated in quotes:

  1. ```sh
  2. linkinator "**/*.md" --markdown
  3. ```

Without the quotes, some shells will attempt to expand the glob paths on their own.  Various shells (bash, zsh) have different, somewhat unpredictable behaviors when left to their own devices.  Using the quotes ensures consistent, predictable behavior by letting the library expand the pattern.

Debugging


Oftentimes when a link fails, it's an easy to spot typo, or a clear 404.  Other times ... you may need more details on exactly what went wrong.  To see a full call stack for the HTTP request failure, use --verbosity DEBUG:

  1. ```sh
  2. linkinator https://jbeckwith.com --verbosity DEBUG
  3. ```

Controlling Output


The --verbosity flag offers preset options for controlling the output, but you may want more control.  Using [jq](https://stedolan.github.io/jq/) and --format JSON - you can do just that!

  1. ```sh
  2. linkinator https://jbeckwith.com --verbosity DEBUG --format JSON | jq '.links | .[] | select(.state | contains("BROKEN"))'
  3. ```

License