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.

JavaScript
// 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.

JavaScript
// 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.

JavaScript
// 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.

JavaScript
// 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.

JavaScript
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 needsJavaScript true and the little text its HTML holds, or answers 404 needs_javascript when 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.
  • tokenCount is 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.txt is respected: a page it closes answers 404 not_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?

SituationUse
You already have clean HTML, or you pick the element yourselfTurndown
Articles, documentation and blog posts from many sitesReadability, then Turndown
Pages that build their text in the browserPlaywright, then the same two
A serverless function or an agent, without parsing code to maintainAn 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.

Every source

YouTube

Instagram

TikTok

Facebook

Google

Threads

LinkedIn

App stores

Steam

X

Pinterest

Airbnb

Real estate

Keywords

Job boards

Eventbrite

Shopify stores

Public tenders

All guides