Extracts the main article from a web page and converts it to Markdown. Used by readstack.io to parse web content.
Contents
- What it does
- Install
- Usage
- API
- How article detection works
- Writing a custom parser
- Contributing
- Fixture pages
- License
Pass in a web page's HTML and URL. The parser will find the main article, strip out unrelated content, and then return it as markdown alongside some page metadata.
It does not download web pages. You should fetch the HTML yourself, then pass it in.
To find the article, it tries three strategies in order and uses the first one that succeeds:
- A custom parser for that specific website, if one exists.
- Built-in article detection, which handles most pages.
- Mozilla Readability, as a fallback.
pnpm add @readstack/parser- Node.js 24 and ESM This package targets Node.js 24 and ships as an ES module. Load it with
import, or withrequireon Node.js 24. - pnpm and
re2One of the parser's dependencies uses re2 to match URLs safely on untrusted pages. re2 needs to build itself when it is installed. pnpm blocks this by default, so the install ends with an error. To fix it, runpnpm approve-buildsand pickre2. The parser still works if you skip this, but it is less protected against harmful pages.
import {parseArticle} from '@readstack/parser'
const url = 'https://example.com/blog/my-post'
const html = await (await fetch(url)).text()
const article = await parseArticle({url, html})
console.log(article.title)
console.log(article.markdown)
console.log(article.meta.readingTimeInSeconds)Finds the article in html and resolves to a ParserOutput object.
| Option | Type | Description |
|---|---|---|
url |
string |
Used to pick a site parser, set meta.domain, and convert relative links and image paths into absolute URLs. |
html |
string |
Full HTML of the page. |
onDebug |
(message: string) => void |
Optional callback that receives debug messages. |
The parser never logs to the console on its own. To inspect what it is doing, pass an onDebug callback:
await parseArticle({url, html, onDebug: (message) => console.log(message)})Returned by parseArticle:
{
title: 'My post',
markdown: 'Some article text...',
meta: {
url: 'https://example.com/blog/my-post',
domain: 'example.com',
readingTimeInSeconds: 240,
processedAt: '2026-12-02T10:00:00.000Z',
// languages detected from any code blocks
codeLanguages: ['javascript'],
// open graph
ogImage: 'https://example.com/images/my-post.png',
ogDescription: 'A short summary of the post.',
},
}Thrown when no article can be found on the page. It usually includes a details property, but it can be missing:
details.parser: The name of the parser that failed.details.candidate(optional): ACandidateSnapshotof the element that came closest to being the article. It includes the element's tag,id,className, text length, and the number of child elements that look like article content. This is useful for debugging why extraction failed.
Other errors (such as an invalid URL) are thrown as standard errors. Check the error type before reading details:
import {ParseError, parseArticle} from '@readstack/parser'
try {
await parseArticle({url, html})
} catch (error) {
if (error instanceof ParseError) {
console.log(error.details?.candidate)
}
throw error
}ParserOutput, ParseErrorDetails, CandidateSnapshot, and OnDebug.
Most websites do not use HTML in a reliable way, so the parser does not automatically trust tags like <article> or <main>.
Instead, it looks for the section of the page with the highest concentration of article content with elements like paragraphs, headings, lists, images, tables, and code blocks. It then cleans up any leftovers like duplicate titles or link-heavy lists.
Most pages work out of the box. Only write a custom parser when a site consistently parses poorly, and handling in DefaultParser would cause it to be too specific or hacky.
A parser is a class in src/parsers/ with two methods:
canParse(url): Returnstrueif this parser handles the given URL. Compare the parsedhostnamerather than the raw URL string so that URLs likehttps://example.com/?u=bbc.co.ukdo not match by mistake.extract({$, url, onDebug}): Receives the cleaned page loaded into Cheerio and returns the element containing the article. Perform whatever operations you want here.
BaseParser automatically handles the title, reading time, metadata, and Markdown conversion.
The simplest approach is to extend DefaultParser, remove the unwanted elements, and let default detection handle the rest. This example follows the same pattern as BbcUkParser:
import type {ExtractParams} from './BaseParser'
import {DefaultParser} from './DefaultParser'
class ExampleParser extends DefaultParser {
canParse(url: string) {
const {hostname} = new URL(url)
return hostname === 'example.com' || hostname.endsWith('.example.com')
}
protected async extract(params: ExtractParams) {
const {$} = params
$('.author-box, .newsletter-signup').remove()
return super.extract(params)
}
}
export {ExampleParser}If a site has an unusual layout, extend BaseParser and select the article element manually. If no article is found, throw a ParseError so the next parser in line can try.
For example, imagine a site that used paragraphs like <div class="para"> instead of <p>. By default detection looks for paragraphs, headings and other article elements, so it finds no article on these pages.
This parser selects the story and turns those divs into paragraphs:
import {ParseError} from '../ParseError'
import {BaseParser, type ExtractParams} from './BaseParser'
class ExampleParser extends BaseParser {
constructor() {
// BaseParser takes default options, and this parser has none
super({})
}
canParse(url: string) {
const {hostname} = new URL(url)
return hostname === 'example.com' || hostname.endsWith('.example.com')
}
protected async extract({$, url, onDebug}: ExtractParams) {
const story = $('.story-body').first()
if (story.length === 0) {
throw new ParseError('no story body found', {
parser: this.constructor.name,
})
}
// the site uses div.para for paragraphs, which detection does not see
const paragraphs = story.find('div.para')
paragraphs.each((_, el) => {
el.tagName = 'p'
})
onDebug?.(`converted ${paragraphs.length} paragraphs: ${url}`)
return story
}
}
export {ExampleParser}- Register it. Add an instance of your parser to the
parsersarray insrc/parsers/registry.tsbeforeDefaultParser. Parsers are tried in order. - Add a test fixture. Save a real HTML page from the site in
src/parsers/fixtures/. - Write tests. Create a test file next to your parser (e.g.,
ExampleParser.test.ts), modeled aftersrc/parsers/BbcUkParser.test.ts. Include one test that checks the extracted Markdown against a snapshot, and one that verifiescanParseURL matching. - Verify the snapshot. Run
pnpm testand review the generated file insrc/parsers/__snapshots__/to make sure the output looks clean.
This project uses pnpm. Pull requests run all of the following checks:
pnpm test # Run tests
pnpm typecheck # Run TypeScript type checking
pnpm lint # Run oxlint and ESLint
pnpm chk # Check Prettier formatting (run `pnpm fmt` to fix)
pnpm build # Build to dist/Commit messages follow Conventional Commits. The commit type determines the version bump when a PR is merged:
- Major release: Breaking changes
- Minor release:
feat(e.g., adding a new site parser) - Patch release:
fix,perf(e.g., fixing how a page is parsed) - No release:
docs,style,refactor,test,build,ci,chore,revert
Test fixture pages contain third-party content. See the fixtures notice for details.