Cheerio HTML Metadata Extraction
Parse fetched HTML with Cheerio to extract OpenGraph metadata, clean text, and attribute values without executing any page scripts.
Code
import * as cheerio from 'cheerio';
const html = await fetch('https://example.com/article')
.then((r) => r.text());
const $ = cheerio.load(html);
const metadata = {
title: $('meta[property="og:title"]').attr('content')
?? $('title').text().trim(),
description: $('meta[name="description"]').attr('content') ?? '',
canonical: $('link[rel="canonical"]').attr('href') ?? null,
image: $('meta[property="og:image"]').attr('content') ?? null,
};
const headings = $('h2')
.map((_, el) => $(el).text().trim())
.get()
.filter((t) => t.length > 0)
.slice(0, 5);
const wordCount = $('article')
.text()
.replace(/\s+/g, ' ')
.trim()
.split(' ')
.filter(Boolean).length;
console.log(JSON.stringify(metadata, null, 2), headings, wordCount);How the snippet works
Every asynchronous step is awaited, so rejections surface where the call happens.
The whole file runs on the top-level bindings declared above: html, metadata, headings, wordCount.
Watch out for
- Plan for an install step:
cheeriois a real dependency, resolved by the package manager. - A browser is the runtime here:
fetchare not available in Node.
Statements that matter
.then((r) => r.text());
.map((_, el) => $(el).text().trim())
.get()
.filter((t) => t.length > 0)
.slice(0, 5);
Interactive Tools for This Topic
HTML Entity Encoder / DecoderEncode the five HTML-significant characters and decode named or numeric entities, with optional numeric encoding for non-ASCII text.Markdown Live PreviewRender Markdown to HTML in real time with a live preview pane. Supports headings, lists, code blocks, links, emphasis, and blockquotes for documentation drafting.YAML Frontmatter ExtractorExtract the YAML frontmatter block from Markdown documents and parse scalars and simple lists into a JSON metadata object.
FAQ
- Does this require external packages?
- Yes — `cheerio`. Add it to your project before running the snippet.
Report a problem with this exampleOpens a pre-filled issue on GitHub.