Wenn du eine Node.js-Anwendung entwickelst, die von Nutzern hochgeladene Dokumente einliest, hast du wahrscheinlich schon auf einen Ordner voller PDFs, DOCX-Dateien und PPTX-Präsentationen geschaut und dich gefragt: Wie normalisiere ich all das in ein Format, das meine LLM-Pipeline tatsächlich verwenden kann?
Dieser Beitrag zeigt die Nutzung der REST-API von AnyMD aus Node.js — mit fetch, axios, TypeScript-Typen, Streaming und Express-Middleware-Mustern für die Dokument-zu-Markdown-Konvertierung im Produktionsmaßstab.
Warum Markdown aus Node.js?
Node.js-Anwendungen verarbeiten Datei-Uploads ganz selbstverständlich — Multer, Busboy, Express-Middleware. Um diese Uploads jedoch in sauberen, strukturierten Text für RAG-Pipelines oder KI-Trainingsdaten umzuwandeln, braucht man meist schwere native Bindings (PyMuPDF, LibreOffice, pandoc), die nicht in eine JS-Laufzeit gehören.
AnyMD bietet dir eine zustandslose HTTP-API. Ein Aufruf, eine Antwort, sauberes Markdown. Keine nativen Abhängigkeiten, keine serverseitigen Formatbibliotheken, keine Python-Subprozesse in deiner Node.js-Anwendung.
Schnellstart mit fetch (ohne Abhängigkeiten)
Node.js 18+ stellt fetch global bereit. Die einfachste einmalige Konvertierung:
const fs = require("fs");
const { readFile } = require("fs/promises");
async function convertToMarkdown(filePath, apiKey) {
const form = new FormData();
form.set("file", new Blob([await readFile(filePath)]), filePath);
const resp = await fetch("https://anymd.net/api/convert", {
method: "POST",
headers: { Authorization: `Bearer ${apiKey}` },
body: form,
});
if (!resp.ok) {
throw new Error(`AnyMD error ${resp.status}: ${await resp.text()}`);
}
return await resp.text();
}
// Usage
const md = await convertToMarkdown("report.docx", "your-api-key");
console.log(md);
Das war's. AnyMD erkennt das Format automatisch anhand der Dateiendung und gibt GitHub-Flavored Markdown zurück.
TypeScript mit typisierten Antworten
Für TypeScript-Projekte ergänzt du passende Rückgabetypen und Fehlerbehandlung:
interface ConversionResult {
markdown: string;
format: string;
pages: number;
duration: number;
}
interface ConversionError {
status: number;
message: string;
}
async function convertToMarkdownTyped(
filePath: string,
apiKey: string
): Promise<ConversionResult> {
const form = new FormData();
const buffer = await fs.promises.readFile(filePath);
form.set("file", new Blob([buffer]), filePath);
const start = performance.now();
const resp = await fetch("https://anymd.net/api/convert", {
method: "POST",
headers: { Authorization: `Bearer ${apiKey}` },
body: form,
});
const duration = performance.now() - start;
if (!resp.ok) {
const err: ConversionError = {
status: resp.status,
message: await resp.text(),
};
throw err;
}
return {
markdown: await resp.text(),
format: filePath.split(".").pop() || "unknown",
pages: parseInt(resp.headers.get("X-Pages") || "0", 10),
duration: Math.round(duration),
};
}
Express-Middleware für Upload-Endpunkte
So bindest du AnyMD mit Multer für Datei-Uploads in einen Express-Server ein:
import express from "express";
import multer from "multer";
import fs from "fs/promises";
const app = express();
const upload = multer({ dest: "/tmp/uploads/" });
const ANYMD_API = "https://anymd.net/api/convert";
app.post("/upload", upload.single("file"), async (req, res) => {
try {
const apiKey = req.headers["authorization"]?.replace("Bearer ", "");
if (!apiKey) return res.status(401).json({ error: "Missing API key" });
const form = new FormData();
const buffer = await fs.readFile(req.file.path);
form.set("file", new Blob([buffer]), req.file.originalname);
const anymdResp = await fetch(ANYMD_API, {
method: "POST",
headers: { Authorization: `Bearer ${apiKey}` },
body: form,
});
if (!anymdResp.ok) {
return res.status(anymdResp.status).json({
error: await anymdResp.text(),
});
}
const markdown = await anymdResp.text();
res.json({ markdown, pages: anymdResp.headers.get("X-Pages") });
} catch (err) {
res.status(500).json({ error: err.message });
} finally {
if (req.file) fs.unlink(req.file.path).catch(() => {});
}
});
app.listen(3000);
Stapelverarbeitung mit axios und Wiederholungsversuchen
Wenn du Hunderte Dokumente verarbeiten musst, sind sequenzielle Aufrufe zu langsam. Hier ist ein paralleler Batch-Prozessor mit axios:
import axios from "axios";
import FormData from "form-data";
import fs from "fs";
import path from "path";
import pLimit from "p-limit";
const API = "https://anymd.net/api/convert";
async function convertOne(filePath, apiKey) {
const form = new FormData();
form.append("file", fs.createReadStream(filePath), path.basename(filePath));
for (let attempt = 0; attempt < 3; attempt++) {
try {
const resp = await axios.post(API, form, {
headers: {
...form.getHeaders(),
Authorization: `Bearer ${apiKey}`,
},
maxContentLength: 50 * 1024 * 1024,
timeout: 30_000,
});
const outPath = filePath.replace(path.extname(filePath), ".md");
fs.writeFileSync(outPath, resp.data);
return { file: path.basename(filePath), ok: true };
} catch (err) {
if (attempt === 2) return { file: path.basename(filePath), ok: false, error: err.message };
const delay = Math.pow(1.5, attempt) * 1000;
await new Promise(r => setTimeout(r, delay));
}
}
}
async function batchConvert(dir, apiKey, concurrency = 10) {
const files = fs.readdirSync(dir).filter(f =>
/\.(docx|pdf|pptx|xlsx|epub|odt|rtf)$/i.test(f)
);
const limit = pLimit(concurrency);
const results = await Promise.all(
files.map(f => limit(() => convertOne(path.join(dir, f), apiKey)))
);
const ok = results.filter(r => r.ok).length;
console.log(`${ok}/${results.length} converted`);
return results;
}
await batchConvert("./documents", "your-api-key", 10);
Streaming großer Dokumente
Für Dokumente über 10 MB solltest du den Streaming-Endpunkt verwenden, damit nicht die gesamte Markdown-Ausgabe im Speicher gepuffert werden muss.
Vergleich mit lokalen Node.js-Bibliotheken
| Format | Node.js-Bibliothek | AnyMD |
|---|---|---|
| DOCX | mammoth — keine Unterstützung für PPTX/PDF/XLSX | Eine API, mehr als 15 Formate |
pdf-parse — verliert Tabellen und Überschriften | GFM, erhält die Struktur | |
| PPTX | pptx2md — nur CLI, keine API | REST-API, asynchrone Pipeline |
| XLSX | xlsx — CSV-Export, kein Markdown | Tabellen → GFM-Tabellen |
| EPUB | epub2md — seit 2022 nicht gepflegt | Aktive, versionierte API |
Leistung: Node.js spricht mit Rust
AnyMD läuft auf einem Rust-/Axum-Backend.
| Format | Dokumentgröße | AnyMD (ms) | Lokale Bibliothek (ms) |
|---|---|---|---|
| DOCX | 50 KB (10 Seiten) | 280 | 620 (mammoth) |
| 120 KB (15 Seiten) | 410 | 2,100 (pdf-parse) | |
| PPTX | 200 KB (20 Folien) | 520 | 1,800 (pptx2md) |
| XLSX | 80 KB (5 Tabellenblätter) | 340 | 950 (xlsx + manuelle Formatierung) |
Von Markdown zur RAG-Pipeline
Sobald deine Node.js-Anwendung sauberes Markdown hat, folgen Chunking und Embedding für die Vektorsuche. Die AnyMD-Ausgabe ist die ideale Eingabe für semantisches Chunking — Überschriftengrenzen, Listenstruktur und Tabellenköpfe bleiben erhalten.
Preise
| Tarif | Seiten/Monat | Maximale Dateigröße | Preis |
|---|---|---|---|
| Kostenlos | 100 | 10 MB | $0 |
| Starter | 500 | 25 MB | $19 |
| Pro | 5,000 | 50 MB | $99 |
| Enterprise | Individuell | Individuell | Individuell |
Ein typisches Dokument wird in weniger als 0,5 Sekunden konvertiert. 100 kostenlose Seiten pro Monat — keine Kreditkarte erforderlich.
Hol dir deinen kostenlosen API-Schlüssel und beginne noch heute, Dokumente aus Node.js in Markdown umzuwandeln.