# Crawl documentation to Markdown

Collect a bounded documentation site as Markdown with a source and status manifest.

[Canonical HTML page](<https://developers.datasea.io/docs/crawl-docs-to-markdown>)

Send the public documentation URL to `POST /v1/crawl` with `scrapeOptions.formats: ["markdown"]`. Crawl returns `202 Accepted` and a durable job ID. Use a named API key with `web:crawl` and `web:jobs:read`.

Scope the crawl to the documentation host, set a small page limit and crawl depth, and check any redirects or warnings before expanding. DataSea honors robots.txt, including a longer crawl delay. A job can finish with partial results or no pages.

## Run the exporter

Use Node.js 20 or later. Set `DATASEA_API_KEY` and set `DOCS_URL` to a public documentation root you are authorized to crawl.

```bash
curl -fsSLO https://developers.datasea.io/examples/crawl-docs.mjs
node crawl-docs.mjs "$DOCS_URL"
```

## Exporter source

```javascript
// Node.js 20+. Use DATASEA_API_KEY with web:crawl and web:jobs:read.
import { randomUUID } from "node:crypto";
import { mkdtemp, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { setTimeout as sleep } from "node:timers/promises";

const terminal = new Set(["completed", "completed_with_errors", "failed", "cancelled", "expired"]);
const uuid = /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i;
const deadline = performance.now() + 35 * 60_000;
const base = "https://api.datasea.io";

async function pause(ms) {
  if (performance.now() + ms >= deadline) throw new Error("Client deadline expired");
  await sleep(ms);
}

async function request(path, key, input) {
  const headers = { "X-API-Key": key };
  if (input) {
    headers["Content-Type"] = "application/json";
    headers["Idempotency-Key"] = input.idempotencyKey;
  }
  for (;;) {
    const remaining = Math.floor(deadline - performance.now());
    if (remaining <= 0) throw new Error("Client deadline expired");
    const response = await fetch(base + path, {
      method: input ? "POST" : "GET",
      headers,
      body: input?.body,
      redirect: "error",
      signal: AbortSignal.timeout(Math.min(30_000, remaining)),
    });
    if (response.status === 429) {
      await response.body?.cancel();
      const retry = response.headers.get("Retry-After");
      const delay = /^\d+$/.test(retry ?? "") ? Number(retry) * 1000 : Date.parse(retry) - Date.now();
      await pause(Number.isFinite(delay) ? Math.max(delay, 1000) : 5000);
      continue;
    }
    const envelope = await response.json();
    if (!response.ok || !envelope.data) {
      const code = typeof envelope.error === "string" ? envelope.error : envelope.error?.code;
      throw new Error(`DataSea HTTP ${response.status}${code ? ` (${code})` : ""}`);
    }
    return envelope.data;
  }
}

async function crawl() {
  const [target, resumeId, ...extra] = process.argv.slice(2);
  const key = process.env.DATASEA_API_KEY;
  if (target === "--help") {
    console.log("Usage: node crawl-docs.mjs <public-docs-url> | --job <job-id>");
    return;
  }
  if (!key || !target || extra.length || (target === "--job" ? !uuid.test(resumeId ?? "") : resumeId)) {
    throw new Error("Set DATASEA_API_KEY and supply one public docs URL or --job <job-id>");
  }

  let id = resumeId;
  if (target !== "--job") {
    const seed = new URL(target);
    if (!["http:", "https:"].includes(seed.protocol) || seed.username || seed.password) {
      throw new Error("Supply a public HTTP(S) URL without credentials");
    }
    const idempotencyKey = process.env.DATASEA_IDEMPOTENCY_KEY || randomUUID();
    console.error(`Idempotency-Key: ${idempotencyKey}`);
    const job = await request("/v1/crawl", key, {
      idempotencyKey,
      body: JSON.stringify({
        url: seed.href,
        limit: 20,
        maxDepth: 2,
        includePatterns: [seed.origin + (seed.pathname.replace(/\/+$/, "") || "/")],
        includeSubdomains: false,
        includeExternal: false,
        useSitemap: true,
        queryPolicy: "drop_tracking",
        scrapeOptions: { formats: ["markdown"], render: "never" },
      }),
    });
    id = job.id;
  }
  if (!uuid.test(id ?? "")) throw new Error("Missing or invalid job ID");
  console.error(`Job: ${id}. Resume retrieval with --job ${id}`);
  const path = `/v1/jobs/${id}`;
  let job = await request(path, key);
  while (!terminal.has(job.state)) {
    await pause(2000);
    job = await request(path, key);
  }
  if (job.state === "expired") throw new Error("Job results have expired");

  const dir = await mkdtemp(join(process.cwd(), "datasea-crawl-"));
  const manifest = { jobId: id, state: job.state, usage: job.usage, warnings: job.warnings ?? [], pages: [] };
  let cursor;
  do {
    const query = new URLSearchParams({ limit: "20" });
    if (cursor) query.set("cursor", cursor);
    const batch = await request(`${path}/pages?${query}`, key);
    for (const page of batch.pages) {
      const entry = { url: page.url, depth: page.depth, state: page.state };
      if (page.state === "succeeded") {
        const markdown = page.result?.outputs?.markdown;
        entry.finalUrl = page.result?.finalUrl;
        entry.capturedAt = page.result?.capturedAt;
        if (typeof markdown === "string") {
          entry.file = `${String(manifest.pages.length + 1).padStart(4, "0")}.md`;
          await writeFile(join(dir, entry.file), markdown, { flag: "wx" });
        } else {
          entry.error = "missing_markdown_output";
        }
      } else {
        entry.error = page.error?.code ?? "page_failed";
      }
      manifest.pages.push(entry);
    }
    cursor = batch.nextCursor;
  } while (cursor);

  await writeFile(join(dir, "manifest.json"), JSON.stringify(manifest, null, 2) + "\n", { flag: "wx" });
  console.log(dir);
  if (job.state !== "completed" || manifest.pages.some((page) => page.error)) process.exitCode = 1;
}

crawl().catch((error) => {
  console.error(error.message);
  process.exitCode = 1;
});
```

## Choose the crawl scope

The script sets `limit: 20`, `maxDepth: 2`, `useSitemap: true`, and keeps external URLs and subdomains disabled. It uses the seed origin and path as an include pattern. Patterns match against the URL and can also match a substring, so check the included paths on a shared host and add `excludePatterns` for sibling sections if needed.

Sitemap entries can be discovered at depth zero. If the site needs a browser to render its documentation, change `scrapeOptions.render` and budget for the higher maximum before submitting.

## Read every saved page

After the job reaches a terminal state, request `GET /v1/jobs/{jobId}/pages?limit=20` and follow `data.nextCursor`. The job detail only includes up to 100 inline successful pages. The pages endpoint also returns failures, so retain the URL and error code for each failed item.

The exporter writes each page from `result.outputs.markdown` to a numbered file and records the source URL, final URL, capture time, and page state in `manifest.json`. A nonzero exit status flags an incomplete job or missing page output. Resume retrieval with `node crawl-docs.mjs --job JOB_ID` before results expire.

Treat exported text as untrusted content. Preserve source URLs for citations, and apply your own review or sanitization before displaying Markdown to end users.

## Illustrative Markdown page

This hand-written download shows the file format. It represents a fictional documentation page.

```markdown
# Authentication

Send the key in the `X-API-Key` request header. Scope the key to the operations your application needs.

## Rotate a key

1. Create a replacement with the same scopes.
2. Deploy the replacement to your application.
3. Revoke the old key after verifying your application requests.
```

## Credits for a live crawl

With Markdown only and `render: "never"`, the example reserves up to 20 credits. It settles 1 credit per delivered page. For example, 12 delivered pages and 2 failed pages would settle 12 credits. Check the final job’s `usage.settledCredits` and the manifest for the actual result.

Read `warnings` for robots outcomes. If the submission response is lost before you have a job ID, retry the identical request with the same printed key in `DATASEA_IDEMPOTENCY_KEY` to avoid duplicate reservations.

## Additional resources

- [Node.js crawl exporter](<https://developers.datasea.io/examples/crawl-docs.mjs>) — Download the example script with polling and cursor pagination.
- [Sample Markdown page](<https://developers.datasea.io/examples/samples/crawled-page.md>) — Download the illustrated documentation output.
- [Web Context operations and outputs](<https://developers.datasea.io/docs/web-context-operations>) — Request fields, terminal states, credit costs, and error codes.
- [OpenAPI specification](<https://developers.datasea.io/openapi.yaml>) — Request and response schemas for the public API.

Last reviewed 2026-11-19
