Skip to content
readstackappPublic

About

Grab the main content of a web page as markdown

Resources

Stars

3 stars

Watchers

0 watching

Forks

Repository files navigation

@readstack/parser

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

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:

  1. A custom parser for that specific website, if one exists.
  2. Built-in article detection, which handles most pages.
  3. Mozilla Readability, as a fallback.

Install

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 with require on Node.js 24.
  • pnpm and re2 One 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, run pnpm approve-builds and pick re2. The parser still works if you skip this, but it is less protected against harmful pages.

Usage

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)

API

parseArticle({url, html, onDebug?})

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)})

ParserOutput

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.',
  },
}

ParseError

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): A CandidateSnapshot of 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
}

Exported Types

ParserOutput, ParseErrorDetails, CandidateSnapshot, and OnDebug.

How article detection works

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.

Writing a custom parser

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): Returns true if this parser handles the given URL. Compare the parsed hostname rather than the raw URL string so that URLs like https://example.com/?u=bbc.co.uk do 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.

Simple

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}

Advanced

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}

Steps to add your parser

  1. Register it. Add an instance of your parser to the parsers array in src/parsers/registry.ts before DefaultParser. Parsers are tried in order.
  2. Add a test fixture. Save a real HTML page from the site in src/parsers/fixtures/.
  3. Write tests. Create a test file next to your parser (e.g., ExampleParser.test.ts), modeled after src/parsers/BbcUkParser.test.ts. Include one test that checks the extracted Markdown against a snapshot, and one that verifies canParse URL matching.
  4. Verify the snapshot. Run pnpm test and review the generated file in src/parsers/__snapshots__/ to make sure the output looks clean.

Contributing

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

Fixture pages

Test fixture pages contain third-party content. See the fixtures notice for details.

License

MIT

About

Grab the main content of a web page as markdown

Resources

Stars

3 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages