How to turn a web page into Markdown in JavaScript for RAG
Checked on 2026-11-24.
For a RAG pipeline in JavaScript you want each page as Markdown: headings, lists, tables and links kept, menus and scripts gone. Turndown converts any HTML to Markdown, and Mozilla's Readability first picks out the article, so in Node.js the usual recipe is Readability on jsdom, then Turndown. Neither runs the page's JavaScript, and neither does the API at the end.
1. Turndown: convert the HTML
Turndown (MIT, version 7.2.5 of November 4, 2026 on npm) converts an HTML string or a DOM node. By default it underlines headings (setext) and indents code blocks; set atx for # headings and fenced for code between backticks. Two other things in its README matter for whole pages. "By default, Turndown does not remove any elements", so you name what to drop. And tables need a plugin: the README uses turndown-plugin-gfm, whose last release on npm, 1.0.2, is from 2018.
// npm install turndown turndown-plugin-gfm
import TurndownService from 'turndown';
import { gfm } from 'turndown-plugin-gfm';
const res = await fetch('https://docs.apify.com/academy', { signal: AbortSignal.timeout(20_000) });
const html = await res.text();
const turndown = new TurndownService({ headingStyle: 'atx', codeBlockStyle: 'fenced', bulletListMarker: '-' });
turndown.remove(['title', 'script', 'style', 'noscript', 'nav', 'footer', 'form', 'button']);
turndown.use(gfm); // pipe tables, strikethrough, task lists
console.log(turndown.turndown(html));We ran this on a saved page. With the defaults, the text of the <title>, the <style> and the <script> elements came out at the top and bottom of the Markdown, and the table came out as one cell per paragraph; with the options and the plugin above, both were clean. The README also warns that its escaping "can be quite aggressive": a heading such as "1. Hello world" becomes 1\. Hello world.
Where it stops: it converts, it does not choose. Menus, cookie notices, sidebars and footers that are not in the elements you remove come out as Markdown like the article. Links stay as written in the page, so relative ones stay relative.
2. Readability: keep only the article
Readability is, in its README's words, "a standalone version of the readability library used for Firefox Reader View" (Apache-2.0, version 0.6.0 on npm). Node.js has no DOM of its own, so the README pairs it with jsdom, and asks you to pass the page's address so relative links become absolute.
// npm install @mozilla/readability jsdom turndown turndown-plugin-gfm
import { Readability, isProbablyReaderable } from '@mozilla/readability';
import { JSDOM } from 'jsdom';
import TurndownService from 'turndown';
import { gfm } from 'turndown-plugin-gfm';
const turndown = new TurndownService({ headingStyle: 'atx', codeBlockStyle: 'fenced', bulletListMarker: '-' });
turndown.remove(['script', 'style', 'noscript']);
turndown.use(gfm);
export function htmlToMarkdown(html, address) {
// The address lets Readability turn relative links into absolute ones
const doc = new JSDOM(html, { url: address }).window.document;
const article = isProbablyReaderable(doc) ? new Readability(doc).parse() : null;
if (!article) {
// Not an article: convert the whole body, menus included
const body = new JSDOM(html, { url: address }).window.document.body;
return { title: null, markdown: turndown.turndown(body) };
}
return { title: article.title, byline: article.byline, markdown: turndown.turndown(article.content) };
}
export async function pageToMarkdown(address) {
const res = await fetch(address, { signal: AbortSignal.timeout(20_000) });
if (!res.ok) throw new Error(`${address} answered ${res.status}`);
return htmlToMarkdown(await res.text(), res.url);
}parse() returns the title, the article as HTML in content, a textContent, its length, an excerpt, the byline, siteName, lang and publishedTime. It works by modifying the DOM, which is why the fallback builds a fresh one. isProbablyReaderable() is, by the README's account, "a quick-and-dirty way" to tell whether parsing is worth it, "likely to produce both false positives and false negatives". jsdom 31 asks for Node.js 22.22.2 or a later 22, 24.15 or a later 24, or 26 and newer.
On our saved page, Readability dropped the menu and the footer, made the links absolute and found the byline. It kept a cookie notice that sat outside the article, and it returned the page's h1 as a second-level heading.
Where it stops: it is built for articles. On a product grid, a pricing table or a search page there may be no article to find, and its charThreshold option, 500 by default, is in the README's words "the number of characters an article must have in order to return a result". Its README also says it does not sanitize: if you show its output in a web page, run it through a sanitizer such as DOMPurify first.
Pages built in the browser
Both libraries read the HTML a server sends. A page that builds its text with JavaScript sends little, and you get little. jsdom can run a page's scripts, but Readability's README says these are disabled by default for security reasons and "we strongly recommend you keep them that way". The route that works is a real browser. Playwright's reference describes page.content() as "Gets the full HTML contents of the page, including the doctype", and that HTML goes through the same function.
// npm i -D playwright
// npx playwright install
import { chromium } from 'playwright';
const address = 'https://example.org';
const browser = await chromium.launch();
const page = await browser.newPage();
await page.goto(address);
const html = await page.content();
await browser.close();
console.log(htmlToMarkdown(html, address).markdown);A browser per page takes far more time and memory than a request, so keep it for the pages that need it.
Chunks for the vector store
Markdown makes chunking simple: cut at the headings, so each chunk keeps its own heading and stays on one subject. A few lines are enough; long sections can be cut again by length.
// One chunk per ## section, so each chunk keeps the heading it belongs to
export function chunkByHeadings(markdown, source) {
return markdown
.split(/\n(?=## )/)
.map((text) => text.trim())
.filter((text) => text.length > 0)
.map((text, index) => ({ id: `${source}#${index}`, source, text }));
}3. An HTTP API, when you would rather not run the pipeline
The Pipefetch page content endpoint fetches one page and returns its content as Markdown, with its menus dropped. It is one fetch, so it runs wherever fetch does, including serverless functions where jsdom and a browser are heavy to ship.
const url = new URL('https://pipefetch.com/v1/web/content');
url.searchParams.set('url', 'https://docs.apify.com/academy');
const res = await fetch(url, {
headers: { 'x-api-key': process.env.PIPEFETCH_API_KEY },
signal: AbortSignal.timeout(90_000),
});
if (res.status === 404) {
const { error } = await res.json();
console.log('Not read:', error.code); // needs_javascript, not_allowed, page_not_found ...: not charged
} else if (!res.ok) {
throw new Error(`Pipefetch answered ${res.status}`);
} else {
const { data } = await res.json();
console.log(data.title, data.wordCount, data.tokenCount);
console.log(data.content); // Markdown, menus dropped
}Next to content you get title, description, language, canonicalUrl, the headings as an outline, a wordCount and a tokenCount; the reference lists every field. Keep the key on your server, not in code that ships to a browser.
Where it stops:
- It does not run JavaScript. A page built in the browser comes back with
needsJavaScripttrue and the little text its HTML holds, or answers 404needs_javascriptwhen it holds none; for those, the Playwright route is the one that works. - Menus are judged from the one page alone, so a stray label or a line of footer text can remain.
tokenCountis an estimate from words and punctuation, not the count of a particular tokenizer.- One request reads one page. Links are not followed, and files such as PDFs are not read.
robots.txtis respected: a page it closes answers 404not_allowed.
A request costs 1 credit and most take 2 to 9 seconds. Every 404 is free. A new account has 100 free credits and needs no card. It is not an official API of the websites it reads, and Pipefetch is not affiliated with them.
Which one should you use?
| Situation | Use |
|---|---|
| You already have clean HTML, or you pick the element yourself | Turndown |
| Articles, documentation and blog posts from many sites | Readability, then Turndown |
| Pages that build their text in the browser | Playwright, then the same two |
| A serverless function or an agent, without parsing code to maintain | An HTTP API such as Pipefetch |
If Readability and Turndown give good Markdown for your pages, there is little reason to pay for an API. For one page by hand, the HTML to Markdown converter runs Turndown in your browser; for Python, see the Python version of this guide. node-html-markdown is another converter on npm, which its README describes as "a fast HTML to markdown converter"; it too converts and does not choose. Converting a page does not change whose text it is: the rights stay with whoever published it.
Try it with 100 free credits. No card needed. No scraper to build or maintain. Get an API key or read the docs.
APIs used in this guide
More Websites guides
- Clearbit Logo API alternatives: get a company logo from its domain
- How to extract email addresses from a website in Python
- How to turn a web page into Markdown in Python
- How to detect what a website is built with, in Python
- How to get the contact emails and phone numbers of websites in Google Sheets
- How to build a LangChain tool that reads web pages and searches Google
- How to extract social media links from a website in Python
- How to get a website's favicon in Python
- How to check robots.txt in Python before you fetch a page
Guides for other sources
Every source
YouTube
- How to get a YouTube transcript in Python
- How to get a YouTube transcript in Node.js
- YouTube API quota exceeded: what the error means and how to fix it
- How to find a YouTube channel ID from a handle or URL
- How to download YouTube subtitles as SRT or VTT
- youtube-transcript-api RequestBlocked or IpBlocked: why it happens and how to fix it
- How to get YouTube comments in Python
- How to search YouTube from Python
- How to list a YouTube channel's videos in Python
- How to summarize a YouTube video with an LLM in Python
- How to get YouTube transcripts and video stats in Google Sheets
- How to get YouTube video views and likes in Python
- How to get YouTube transcripts in n8n, Make and Zapier
- LangChain YoutubeLoader fails on a server: why, and a loader that works
- How to get a YouTube channel's subscriber count in Python
- How to give Claude or Cursor access to YouTube (MCP server)
- How to get YouTube comments in Node.js
- How to analyze YouTube comments with an LLM in Python
- How to list a YouTube channel's Shorts in Python
- How to search YouTube from JavaScript
- How to get an Instagram follower count in Python
- Instagram Basic Display API alternatives: what to use after the shutdown
- Instaloader 401 Unauthorized, 429 and "Login required": what to do
- How to calculate an Instagram engagement rate in Python
- How to get an Instagram follower count in Node.js
- How to get Instagram follower counts in Google Sheets
- How to get Instagram Reel views in Python
TikTok
- How to get a TikTok video's views and likes in Python
- How to get the comments of a TikTok video in Python
- How to get a TikTok follower count in Python
- TikTok Research API: who can get access, and what to do if you cannot
- How to get TikTok video views, likes and shares in Node.js
- How to get TikTok views, likes and follower counts in Google Sheets
- How to get a Facebook Page's posts without app review
- Is there a Facebook Marketplace API?
- Facebook Groups API alternatives after its removal in 2024
- How to get a Facebook Page's follower count and contact details in Python
- How to get Google search results in Python
- pytrends 429 TooManyRequestsError: what it means and what to do
- How to get Google Trends data in Python
- Why is Wyoming first in Google Trends?
- How to get Google search results in Node.js
- How to get Google search results into Google Sheets
- How to give an LLM live Google results with tool calling
Threads
- How to get LinkedIn company data in Python
- How to search LinkedIn jobs from Python
- How to get a LinkedIn company page's latest posts in Python