I want to sleep better at night, I want to know, everyone who is reading one of the many README files in my GitHub repositories has correct URLs. I love adding links to examples, blog posts, other repos - and I hate when a link is incorrect. In this blog post I will show how to check URLs from Markdown files.
- Install markdown-link-check with
1 | npm i -D markdown-link-check |
- Add NPM script for finding all top-level Markdown files (you can modify
find
command [1]](https://www.computerhope.com/unix/ufind.htm), 2 to find more files, if needed). Don't forget to escape\
characters.
1 | { |
Notice both external and local links are checked, but not the anchor tags ⚠️.
You can check URLs on Mac and Linux with npm run check:markdown
command:
- Call the same script on CI to avoid breaking the links in the future
1 | - run: npm run check:markdown |
We can even find all Markdown files, while excluding node_modules
folder with command
1 | find . -type f -name '*.md' ! -path './node_modules/*' ! -path './examples/*' -exec npx markdown-link-check --quiet {} \; |
Exit code
We have a problem ... the find -exec
will feed each file to markdown-link-check
and if one has an error, it just continues onto the next Markdown file, swallowing the error.
Instead, let's find all files likes this
1 | find . -type f -name '*.md' ! -path './node_modules/*' |
This prints each found filename per line like this
1 | find . -type f -name '*.md' ! -path './node_modules/*' |
We can feed these lines into xargs program using -L1
argument (one argument per lint).
1 | find . -type f -name '*.md' ! -path './node_modules/*' | xargs -L1 npx markdown-link-check --quiet |
Now we are talking
1 | find . -type f -name '*.md' ! -path './node_modules/*' | xargs -L1 npx markdown-link-check --quiet |
The search fails if any of the links are bad. Now I can sleep tight.
See example in cypress-docker-images