Getting started and guides: what Doc-chunk is, installation, and how to use chunkDocument and chunkDocuments # Introduction > What Doc-chunk is, the problems it solves, and when to use something else. Doc-chunk is a TypeScript library that splits documents into chunks for retrieval-augmented generation (RAG). You pass it a PDF, an Office file, Markdown, or plain text, and it returns chunks with their text, the headings they belong to, and stable ids. Everything runs on your machine. ```ts import { chunkDocument } from "docchunk"; const { chunks } = await chunkDocument({ path: "handbook.pdf" }); ``` ## The problem [Section titled “The problem”](#the-problem) A RAG system answers a question by finding the most relevant passages in your documents and passing them to a language model. Whole documents are too long to embed or to send to the model, so they are split into chunks first. The quality of those chunks decides what the search can find, and so what the model can answer. Getting good chunks takes more work than it first appears. **Each format needs its own parser.** PDFs, Word files, slides, and spreadsheets each need a different tool, and each tool returns text in a different shape. Some of the easiest options are hosted APIs, which means sending your documents to someone else’s server. **Simple splitters ignore structure.** Cutting text every 1,000 characters splits sentences in half, separates table rows from their header, breaks code blocks, and joins the end of one section to the start of the next. A chunk like that is a poor match for any question. **Chunks lose their context.** A chunk that says “Refunds take 5 business days” is much more useful when you know it came from *Returns policy > Refunds*. Most splitters drop the headings. **Ids that change force a full re-index.** If chunk ids are random, or change whenever anything in the file changes, you have to embed every chunk again after a one-line edit. Embedding costs time and money. **Different retrieval setups need different chunks.** Small chunks match questions precisely, and large chunks give the model enough context to answer. Many setups need both, linked to each other. ## What Doc-chunk does [Section titled “What Doc-chunk does”](#what-doc-chunk-does) Doc-chunk converts every supported format to Markdown, parses it once into blocks (headings, paragraphs, lists, tables, code), and splits it with the strategy you choose. * **One function for every format.** PDF, Word, PowerPoint, Excel, OpenDocument, RTF, EPUB, CSV, Markdown, and plain text all go through `chunkDocument` and return the same result. * **Splitting that follows the document’s structure.** The default strategy keeps paragraphs, lists, tables, and code blocks whole, and never puts two sections in one chunk. A table that is too large is split by rows, with the header repeated in each piece. * **Heading paths.** Every chunk lists the headings above it, such as `["Returns policy", "Refunds"]`, so you can store them as metadata or add them to the text before embedding. * **Stable ids.** The same document and options always give the same chunk ids, on Node.js and on Bun. Each chunk also has a hash of its text, so you can tell which chunks changed and re-embed only those. * **11 strategies.** From fixed-size cuts to sentence windows and parent-child chunks, all through the same function and with the same output. * **Fully local.** No server, no API key, no network requests, and no telemetry. PDFs and Office files are converted by [anydoc](https://github.com/firecrawl/anydoc), which runs locally. Markdown and text files are read as they are. ## When to use something else [Section titled “When to use something else”](#when-to-use-something-else) Doc-chunk is not a good fit in these cases: * **Scanned documents.** Doc-chunk does not do OCR. A PDF without a text layer returns no chunks and a `NO_TEXT_LAYER` warning. Run OCR first, then pass the text to Doc-chunk. * **Sizes in tokens.** Sizes are counted in characters. If a chunk must never go over your embedding model’s token limit, leave some margin (see [Sizes are in characters](../how-it-works/#sizes-are-in-characters)) or count tokens after chunking. * **Browsers, Deno, and edge runtimes.** Doc-chunk runs on Node.js 22.12 or later, and on Bun. * **HTML pages.** HTML is not a supported input. Convert pages to Markdown first. * **Semantic chunking.** Doc-chunk splits by structure and size. It does not use embeddings to find topic changes, and it never calls a model. The full list is on the [Limitations](../limitations/) page. ## Next steps [Section titled “Next steps”](#next-steps) * [Quickstart](../quickstart/): install Doc-chunk and chunk your first document. * [How it works](../how-it-works/): the steps from file to chunks, and the ideas the rest of the docs rely on. # Quickstart > Install Doc-chunk and turn your first document into chunks in a few minutes. This page takes you from installing Doc-chunk to reading your first chunks. ## Requirements [Section titled “Requirements”](#requirements) * Node.js 22.12 or later, or Bun 1.x. * An ES module or CommonJS project. Both work. ## Install [Section titled “Install”](#install) * npm ```sh npm install docchunk ``` * pnpm ```sh pnpm add docchunk ``` * yarn ```sh yarn add docchunk ``` * bun ```sh bun add docchunk ``` TypeScript types are included. You don’t need a separate `@types` package. ## Chunk a file [Section titled “Chunk a file”](#chunk-a-file) Pass a file path to `chunkDocument`: index.ts ```ts import { chunkDocument } from "docchunk"; const { chunks } = await chunkDocument({ path: "handbook.pdf" }); console.log(chunks); ``` `chunkDocument` reads the file, detects its format, converts it to Markdown, and splits it with the default strategy, `structure`. Besides `chunks`, the result has three more fields: | Field | Contents | | ---------- | ------------------------------------------------------------------------------------ | | `document` | The document’s id, format, and the Markdown the chunks were cut from. | | `stats` | The number of chunks, their smallest, largest, and average size, and the time taken. | | `warnings` | Problems that didn’t stop chunking, such as a scanned PDF with no text. | The same call works for `.docx`, `.pptx`, `.xlsx`, `.md`, `.txt`, and the other [supported formats](../reference/formats/). In a CommonJS project, load the library with `require`. Everything else is the same. ```js const { chunkDocument } = require("docchunk"); ``` ## Chunk Markdown from a string [Section titled “Chunk Markdown from a string”](#chunk-markdown-from-a-string) If your text is already in memory, pass it as `content` with its `format`, either `"markdown"` or `"text"`: index.ts ```ts import { chunkDocument } from "docchunk"; const markdown = `# Returns policy You can return most items within 30 days of delivery. ## Start a return Sign in, open **Orders**, and choose the item you want to return. ## Refunds We refund the original payment method within 5 business days.`; const { chunks } = await chunkDocument({ content: markdown, format: "markdown" }); for (const chunk of chunks) { console.log(chunk.headingPath.join(" > ")); console.log(chunk.text); console.log("---"); } ``` Output: ```txt Returns policy # Returns policy You can return most items within 30 days of delivery. --- Returns policy > Start a return ## Start a return Sign in, open **Orders**, and choose the item you want to return. --- Returns policy > Refunds ## Refunds We refund the original payment method within 5 business days. --- ``` Each section became its own chunk. The `structure` strategy never puts two sections in one chunk, even when they would fit, so a chunk is always about one topic. ## Read a chunk [Section titled “Read a chunk”](#read-a-chunk) Here is the second chunk from the example above, printed with `console.log(JSON.stringify(chunks[1], null, 2))`: ```json { "id": "cf2dc8b73713ce568741", "text": "## Start a return\n\nSign in, open **Orders**, and choose the item you want to return.", "index": 1, "start": 73, "end": 157, "charCount": 84, "headingPath": [ "Returns policy", "Start a return" ], "blockTypes": [ "heading", "paragraph" ], "contentHash": "264d608f5e01b4272d5a", "metadata": {} } ``` The fields you’ll use first: * `text` is what you embed and send to the model. * `headingPath` is the list of headings above the chunk. Store it with the embedding, or add it to the text with the [`headingPrefix`](../guides/chunk-document/#options-every-strategy-accepts) option. * `id` is stable: the same document and options always give the same id. Use it as the key in your vector database. * `contentHash` is a hash of `text`. When you re-index, compare it with the stored hash to find the chunks that changed. `start` and `end` are positions in `document.markdown`, the Markdown the chunk was cut from. [Chunk a document](../guides/chunk-document/#the-result) describes every field. ## Choose a strategy [Section titled “Choose a strategy”](#choose-a-strategy) The default strategy, `structure`, works well for most documents. To use another one, pass `strategy` in the options: ```ts import { chunkDocument } from "docchunk"; const { chunks } = await chunkDocument( { path: "manual.docx" }, { strategy: "heading" }, ); ``` Some common choices: | If you want | Use | | -------------------------------------------------------------------- | ------------------------- | | Good general-purpose chunks | `structure` (the default) | | One chunk per section of a manual or guide | `heading` | | Small chunks for search, each linked to a larger chunk for the model | `parent-child` | | One sentence per chunk, with the sentences around it as context | `sentence-window` | See [Strategies](../strategies/) for all 11, and help choosing. ### Set the chunk size [Section titled “Set the chunk size”](#set-the-chunk-size) Sizes are in characters, not tokens. The default `size` for `structure` is 1,500 characters: ```ts const { chunks } = await chunkDocument({ path: "handbook.pdf" }, { size: 1000 }); ``` For English prose, a limit of about three characters per token keeps chunks within your embedding model’s limit. For example, 1,500 characters for a model that accepts 512 tokens. Use less for code and for languages that don’t use the Latin alphabet, which need more tokens per character. ## TypeScript: `chunks[0]` may be undefined [Section titled “TypeScript: chunks\[0\] may be undefined”](#typescript-chunks0-may-be-undefined) If your `tsconfig.json` enables `noUncheckedIndexedAccess`, TypeScript types `chunks[0]` as `Chunk | undefined`, because the array can be empty. For example, a document with no text returns no chunks. Loop over the chunks, or check the value before you use it: ```ts for (const chunk of chunks) { console.log(chunk.text); } const first = chunks[0]; if (first !== undefined) { console.log(first.text); } ``` ## Next steps [Section titled “Next steps”](#next-steps) * [How it works](../how-it-works/) explains heading paths, sizes, and ids. * [Chunk a document](../guides/chunk-document/) covers sources, formats, options, warnings, and errors. * [Chunk many documents](../guides/chunk-documents/) shows how to process a folder of files. # How it works > The steps from file to chunks, and the ideas the other pages rely on. This page explains what happens when you call `chunkDocument`, and the ideas the rest of the documentation refers to: sections, heading paths, sizes, and ids. ## From file to chunks [Section titled “From file to chunks”](#from-file-to-chunks) ```txt source → detect format → convert to Markdown → normalize → parse into blocks → split → finalize ``` 1. **Read the source.** A source is a file path, bytes in memory, or a string. See [Chunk a document](../guides/chunk-document/#sources). 2. **Detect the format.** Doc-chunk uses the `format` you pass, if any. Otherwise it looks at the file name for `.md`, `.markdown`, `.txt`, and `.csv`, and then at the file’s content. 3. **Convert to Markdown.** PDF, Word, PowerPoint, Excel, OpenDocument, RTF, EPUB, and CSV files are converted to Markdown by [anydoc](https://github.com/firecrawl/anydoc), on your machine. Markdown and plain text are used as they are. 4. **Normalize.** Windows (`\r\n`) and old Mac (`\r`) line endings become `\n`, and a byte order mark at the start is removed. The result is returned as `document.markdown`. 5. **Parse into blocks.** The Markdown is parsed once into a list of top-level blocks: headings, paragraphs, lists, tables, code blocks, block quotes, and a few rarer kinds. Plain text is not parsed as Markdown. It is split into paragraphs at blank lines, and characters like `#` and `*` stay as text. 6. **Split.** The [strategy](../strategies/) chooses where each chunk starts and ends. 7. **Finalize.** Doc-chunk builds each chunk’s text, id, and content hash, then the stats and warnings. Parsing happens once per document. Strategies work on the parsed blocks and their positions, so they never parse the text again. ## Positions refer to `document.markdown` [Section titled “Positions refer to document.markdown”](#positions-refer-to-documentmarkdown) Each chunk’s `start` and `end` are character positions in `document.markdown`, not in the original file. For a PDF or Word file, `document.markdown` is the converted Markdown. For most chunks, `text` is exactly `document.markdown.slice(start, end)`. There are two exceptions: * With the `headingPrefix` option, the heading path is added before the text. * When a large table or code block is split, each piece repeats the table header or the code fence, which lie outside its range. See [Blocks larger than the size limit](#blocks-larger-than-the-size-limit). ## Sections and heading paths [Section titled “Sections and heading paths”](#sections-and-heading-paths) Headings divide a document into sections. The `headingLevel` option sets which headings start a new section: headings at that level or higher do, and deeper headings stay inside the section they are in. The default is 3, so `#`, `##`, and `###` start sections, and `####` to `######` do not. The `structure` strategy never puts two sections in one chunk. Take this document, chunked with the default options: ```ts import { chunkDocument } from "docchunk"; const markdown = `# Guide Intro text. ## Setup Install it. ### Linux Use the package manager. #### Ubuntu Run apt.`; const { chunks } = await chunkDocument({ content: markdown, format: "markdown" }); for (const chunk of chunks) { console.log(chunk.headingPath); } ``` It gives three chunks, one per section. The `####` heading doesn’t start a section, so *Ubuntu* stays in the *Linux* chunk: ```txt [ 'Guide' ] [ 'Guide', 'Setup' ] [ 'Guide', 'Setup', 'Linux' ] ``` With `{ headingLevel: 2 }`, the `###` heading no longer starts a section either, so *Linux* and *Ubuntu* join the *Setup* chunk: ```txt [ 'Guide' ] [ 'Guide', 'Setup' ] ``` Each list is a chunk’s `headingPath`: the headings above the start of the chunk, outermost first. Heading text is plain text, with Markdown formatting such as `**` or links removed. Plain text documents have no headings, so their chunks have an empty `headingPath`. ### Adding the heading path to the text [Section titled “Adding the heading path to the text”](#adding-the-heading-path-to-the-text) An embedding of “Install it.” carries no hint that it’s about setting up a guide. The `headingPrefix` option adds the heading path to the start of each chunk’s text, joined with `>` and followed by a blank line. With the same document: ```ts const { chunks } = await chunkDocument( { content: markdown, format: "markdown" }, { headingPrefix: true }, ); console.log(chunks[1]?.text); ``` ```txt Guide > Setup ## Setup Install it. ``` The prefix counts toward the size limit. Doc-chunk reserves room for the longest heading path in the document, so prefixed chunks still fit within `size`. ## Sizes are in characters [Section titled “Sizes are in characters”](#sizes-are-in-characters) Every size option (`size`, `minSize`, `overlapChars`, `parentSize`, `childSize`, and the others) is a number of characters. A chunk’s size is the length of its `text`, including: * Markdown syntax, such as `## `, `**`, table pipes, and code fences. * Text repeated from the previous chunk, when you use `overlapChars`. * The heading path, when you use `headingPrefix`. Doc-chunk doesn’t count tokens. For English prose, a size of about three times your embedding model’s token limit keeps chunks under it: 1,500 characters for a model that accepts 512 tokens. Code and languages that don’t use the Latin alphabet use more tokens per character, so use a smaller size for them. Some strategies have no size limit by default: `heading` gives one chunk per section, and `paragraph` and `sentence` give one chunk per paragraph or sentence. If one of those chunks is longer than 8,000 characters, the result includes a `LARGE_CHUNK` warning. Set `size` to split long sections. ## Blocks larger than the size limit [Section titled “Blocks larger than the size limit”](#blocks-larger-than-the-size-limit) The `structure` strategy packs whole blocks into chunks. When a single block is larger than `size`, it is split along its own structure: | Block | Split by | | ------------------------- | -------------------------------------------------------- | | Table | Rows. Each piece repeats the header row. | | List | Items. | | Code block | Lines. Each piece repeats the opening and closing fence. | | Paragraph and other prose | Sentences, then words. | For example, this table is 142 characters long, and `size` is 100: ```ts import { chunkDocument } from "docchunk"; const table = `| Plan | Price | Storage | | --- | --- | --- | | Free | $0 | 5 GB | | Personal | $4 | 100 GB | | Team | $12 | 1 TB | | Business | $25 | 5 TB |`; const { chunks } = await chunkDocument( { content: table, format: "markdown" }, { size: 100, minSize: 50 }, ); for (const chunk of chunks) { console.log(chunk.text); console.log("---"); } ``` It is split into two chunks, and each one is a complete table with the header: ```txt | Plan | Price | Storage | | --- | --- | --- | | Free | $0 | 5 GB | | Personal | $4 | 100 GB | --- | Plan | Price | Storage | | --- | --- | --- | | Team | $12 | 1 TB | | Business | $25 | 5 TB | --- ``` If a single row, item, line, or word is still larger than `size`, Doc-chunk cuts it at the size limit and adds an `OVERSIZED_BLOCK` warning that points to the chunk. The `heading`, `paragraph`, `sentence`, `parent-child`, and `hierarchical` strategies split large blocks the same way when they have a size limit. The `fixed`, `fixed-overlap`, and `sliding-window` strategies ignore structure and cut the text at the size limit. ## Sentences [Section titled “Sentences”](#sentences) The `sentence` and `sentence-window` strategies, and overlap in `structure`, `paragraph`, and `sentence`, work with whole sentences. Doc-chunk finds sentence boundaries with the JavaScript `Intl.Segmenter` API. A table or a code block counts as a single sentence, so it is never cut in the middle. `Intl.Segmenter` sometimes ends a sentence after an abbreviation such as “Dr.” or “e.g.”. ## Ids and content hashes [Section titled “Ids and content hashes”](#ids-and-content-hashes) Each chunk has two hashes: * `id` identifies the chunk. It is built from the document’s id, the options that affect chunking, the chunk’s `start` and `end`, and its level. The `metadata` and `signal` options don’t affect it. * `contentHash` is a hash of the chunk’s `text` alone. Both are the first 20 hexadecimal characters of a SHA-256 hash. They don’t depend on the runtime or the machine: the same document and options give the same values on Node.js and on Bun. The document’s id is a hash of `document.markdown`, so any edit to the document changes every chunk `id`. If you pass your own `documentId`, such as a file path or a database key, a chunk keeps its id as long as its `start` and `end` don’t change. An edit changes the positions of the chunks after it, so their ids change too. `contentHash` only changes when the chunk’s text changes, wherever it is in the document. | After you change | `id` | `contentHash` | | ---------------------------------- | --------------------------------------- | ------------------------------------------ | | Nothing | Same | Same | | Only `metadata` | Same | Same | | The strategy or a size option | Changes | Changes if the text changes | | The document, without `documentId` | Changes for every chunk | Changes only for chunks whose text changed | | The document, with `documentId` | Changes for chunks whose position moved | Changes only for chunks whose text changed | To re-index a document, compare each chunk’s `contentHash` with the one you stored, and embed only the chunks that differ. [Chunk a document](../guides/chunk-document/#ids-and-re-indexing) shows a full example. ## Levels, parents, and children [Section titled “Levels, parents, and children”](#levels-parents-and-children) Most strategies return a flat list of chunks that don’t overlap. Two strategies return chunks at several sizes, where a large chunk contains smaller ones: * `parent-child` returns two levels: large parent chunks, and small child chunks inside them. * `hierarchical` returns as many levels as you ask for, or one level per heading depth. These chunks have three more fields: | Field | Meaning | | ---------- | ---------------------------------------------------------------------- | | `level` | `0` for the largest chunks, `1` for the chunks inside them, and so on. | | `parentId` | The `id` of the chunk that contains this one. Not set at level 0. | | `childIds` | The `id`s of the chunks this one contains. | All levels are returned in one list, sorted by position in the document and then by level, so a parent always comes before the chunks inside it. A common pattern is to embed only the children, and send a matching child’s parent to the model: ```ts import { chunkDocument } from "docchunk"; const { chunks } = await chunkDocument( { path: "policy.pdf" }, { strategy: "parent-child" }, ); const children = chunks.filter((chunk) => chunk.level === 1); const chunksById = new Map(chunks.map((chunk) => [chunk.id, chunk])); // After a search returns a child chunk: // const parent = chunksById.get(child.parentId); ``` To work with the chunks as a tree instead, pass them to [`buildChunkTree`](../reference/build-chunk-tree/). # Chunk a document > Chunk one document from a file path, bytes, or a string, and read the result. `chunkDocument` turns one document into chunks. This guide covers where the document can come from, which formats are supported, what the result contains, and how to handle warnings and errors. ```ts import { chunkDocument } from "docchunk"; const result = await chunkDocument(source, options); ``` The first argument is the [source](#sources). The second is optional: the [strategy](#choosing-a-strategy) and its options, plus the [options every strategy accepts](#options-every-strategy-accepts). The function returns a promise of the [result](#the-result). ## Sources [Section titled “Sources”](#sources) A source is one of three objects: | Source | Use it for | | ------------------------------- | ----------------------------------------------------------------------------------- | | `{ path }` | A file on disk. | | `{ bytes, filename?, format? }` | A file you already have in memory, such as an upload or a file from object storage. | | `{ content, format }` | Markdown or plain text in a string. | ### A file path [Section titled “A file path”](#a-file-path) ```ts const result = await chunkDocument({ path: "docs/handbook.pdf" }); ``` A relative path is resolved against the current working directory. If the file doesn’t exist, or the path is a folder, `chunkDocument` throws a `DocchunkError` with the code `FILE_NOT_FOUND`. `result.document.sourcePath` is set to the path you passed. ### Bytes [Section titled “Bytes”](#bytes) Pass the file’s bytes as a `Uint8Array`. A Node.js `Buffer` is a `Uint8Array`, so the result of `readFile` works as it is: ```ts import { readFile } from "node:fs/promises"; import { chunkDocument } from "docchunk"; const bytes = await readFile("notes.md"); const result = await chunkDocument({ bytes, filename: "notes.md" }); console.log(result.document.sourceFormat); console.log(result.chunks[0]?.text); ``` ```txt markdown # Notes Meeting moved to Friday. ``` PDF and Office files are recognized from their content, so `filename` and `format` are optional for them. Markdown, plain text, and CSV have no signature in their content: pass a `filename` with the right extension, or a `format`. Without either, `chunkDocument` throws an `UNSUPPORTED_FORMAT` error. ```ts const result = await chunkDocument({ bytes, format: "csv" }); ``` ### A string [Section titled “A string”](#a-string) When the text is already in memory, pass it as `content`, with `format` set to `"markdown"` or `"text"`: ```ts const result = await chunkDocument({ content: markdown, format: "markdown" }); ``` The format changes how the text is read. Markdown is parsed into headings, lists, tables, and other blocks. Plain text is split into paragraphs at blank lines, and nothing else is treated as syntax: ```ts import { chunkDocument } from "docchunk"; const content = "# Not a heading\n\n* not a list item"; const asMarkdown = await chunkDocument({ content, format: "markdown" }); const asText = await chunkDocument({ content, format: "text" }); console.log(asMarkdown.chunks.map((chunk) => chunk.blockTypes)); console.log(asText.chunks.map((chunk) => chunk.blockTypes)); ``` ```txt [ [ 'heading', 'list' ] ] [ [ 'paragraph' ] ] ``` Use `"text"` for text that isn’t Markdown, such as logs or transcripts, so that a line starting with `#` doesn’t become a heading. ## Formats [Section titled “Formats”](#formats) | Format | Extensions | Notes | | ------------ | ---------------------- | ---------------------------------------------------- | | PDF | `.pdf` | Text-based PDFs only. Images are ignored. | | Word | `.docx`, `.doc` | | | PowerPoint | `.pptx`, `.ppt` | | | Excel | `.xlsx`, `.xls` | Each sheet becomes a Markdown table. | | OpenDocument | `.odt`, `.ods`, `.odp` | | | RTF | `.rtf` | | | EPUB | `.epub` | | | CSV | `.csv` | Needs a `.csv` file name or `format: "csv"`. | | Markdown | `.md`, `.markdown` | Not converted. | | Plain text | `.txt` | Not converted. Split into paragraphs at blank lines. | ### How the format is detected [Section titled “How the format is detected”](#how-the-format-is-detected) Doc-chunk uses the first of these that gives an answer: 1. The `format` in the source, if you passed one. 2. A `.md`, `.markdown`, `.txt`, or `.csv` file name. 3. The file’s content. PDF, Office, OpenDocument, EPUB, and RTF files each start with a recognizable signature. 4. Any other file extension. If none of them works, `chunkDocument` throws an `UNSUPPORTED_FORMAT` error that asks you to pass `format`. ### Conversion [Section titled “Conversion”](#conversion) Every format except Markdown and plain text is converted to Markdown by [anydoc](https://github.com/firecrawl/anydoc) before chunking. anydoc runs on your machine, with native binaries for macOS, Linux, and Windows x64. It’s only loaded when a document needs converting, so projects that chunk only Markdown and text never load it. The converted Markdown is returned as `document.markdown`, and chunk positions refer to it. For example, a CSV file becomes a Markdown table: ```ts import { chunkDocument } from "docchunk"; const bytes = new TextEncoder().encode("a,b\n1,2\n"); const result = await chunkDocument({ bytes, format: "csv" }); console.log(result.document.markdown); ``` ```md | a | b | | --- | --- | | 1 | 2 | ``` ### Scanned PDFs [Section titled “Scanned PDFs”](#scanned-pdfs) Doc-chunk doesn’t do OCR. PDFs with text work as usual, and images on their pages are ignored. But if any page has no text layer, because it’s scanned or is only an image, the whole PDF gives no chunks, and the result has a `NO_TEXT_LAYER` warning that lists the pages. The same happens when a page is mostly covered by an image, or when a PDF has fewer than 100 characters of text in total. If you need to index scanned documents, run them through an OCR tool first and pass the text to Doc-chunk as `content`. ## Choosing a strategy [Section titled “Choosing a strategy”](#choosing-a-strategy) Without options, `chunkDocument` uses the `structure` strategy, which works well for most documents. To choose another, pass `strategy` and that strategy’s options: ```ts const result = await chunkDocument( { path: "manual.docx" }, { strategy: "heading", headingLevel: 2 }, ); ``` Each strategy accepts its own options. In TypeScript, once you set `strategy`, the editor suggests only that strategy’s options and flags any others. At runtime, an option the strategy doesn’t accept throws an `INVALID_OPTIONS` error. [Strategies](../../strategies/) describes all 11 and helps you choose. ## The result [Section titled “The result”](#the-result) `chunkDocument` returns an object with four fields: ```ts import { chunkDocument } from "docchunk"; const markdown = `# Returns policy You can return most items within 30 days of delivery. ## Refunds We refund the original payment method within 5 business days.`; const { document, stats, warnings } = await chunkDocument({ content: markdown, format: "markdown" }); console.log(document.id, document.sourceFormat, document.charCount); console.log(stats.count, stats.minChars, stats.maxChars, stats.avgChars); console.log(warnings); ``` ```txt 0a124c7110480079c570 markdown 146 2 71 73 72 [] ``` ### `chunks` [Section titled “chunks”](#chunks) The chunks, in document order. Each chunk has these fields: | Field | Type | Description | | ------------- | ---------- | ------------------------------------------------------------------------------------------------------------- | | `id` | `string` | Stable id. See [Ids and re-indexing](#ids-and-re-indexing). | | `text` | `string` | The chunk’s text, in Markdown. | | `index` | `number` | Position in the `chunks` array, starting at 0. | | `start` | `number` | Start position in `document.markdown`, in characters. | | `end` | `number` | End position in `document.markdown`, in characters. Not included in the chunk. | | `charCount` | `number` | Length of `text` in characters. | | `headingPath` | `string[]` | The headings above the start of the chunk, outermost first. | | `blockTypes` | `string[]` | The kinds of blocks the chunk contains, such as `"heading"`, `"paragraph"`, `"list"`, `"table"`, or `"code"`. | | `contentHash` | `string` | A hash of `text`. | | `metadata` | `object` | A copy of the `metadata` option. `{}` when you don’t pass one. | | `contextText` | `string` | The sentences around the chunk. Set by `sentence-window` only. | | `level` | `number` | Nesting level, `0` for the largest chunks. Set by `parent-child` and `hierarchical` only. | | `parentId` | `string` | The `id` of the chunk that contains this one. Set by `parent-child` and `hierarchical` only. | | `childIds` | `string[]` | The `id`s of the chunks inside this one. Set by `parent-child` and `hierarchical` only. | For most chunks, `text` is exactly `document.markdown.slice(start, end)`. It differs when you use `headingPrefix`, and for pieces of a table or code block that was too large for one chunk, which repeat the table header or code fence. See [How it works](../../how-it-works/#positions-refer-to-documentmarkdown). ### `document` [Section titled “document”](#document) | Field | Type | Description | | -------------- | -------- | --------------------------------------------------------------------------------------------------- | | `id` | `string` | The `documentId` option, or a hash of `markdown`. | | `markdown` | `string` | The document as Markdown, after conversion and normalization. Chunk positions refer to this string. | | `sourceFormat` | `string` | The format of the original document, such as `"pdf"` or `"docx"`. | | `sourcePath` | `string` | The file path, when the source was a path. | | `charCount` | `number` | Length of `markdown` in characters. | ### `stats` [Section titled “stats”](#stats) | Field | Type | Description | | ------------ | -------- | -------------------------------------------------- | | `count` | `number` | Number of chunks. | | `minChars` | `number` | Characters in the smallest chunk. | | `maxChars` | `number` | Characters in the largest chunk. | | `avgChars` | `number` | Average characters per chunk, rounded. | | `durationMs` | `number` | Time taken, in milliseconds, including conversion. | When there are no chunks, all the size fields are `0`. ### `warnings` [Section titled “warnings”](#warnings) Problems that didn’t stop chunking. See [Warnings](#warnings). ## Options every strategy accepts [Section titled “Options every strategy accepts”](#options-every-strategy-accepts) These options work with every strategy. ### `metadata` [Section titled “metadata”](#metadata) An object copied onto every chunk. Use it for anything you want to store alongside the embedding, such as the source file or an access group: ```ts import { chunkDocument } from "docchunk"; const { chunks } = await chunkDocument( { content: "# Leave\n\nYou get 25 days of paid leave each year.", format: "markdown" }, { metadata: { source: "hr-handbook", team: "people" } }, ); console.log(chunks[0]?.metadata); ``` ```txt { source: 'hr-handbook', team: 'people' } ``` Changing `metadata` doesn’t change chunk ids. ### `documentId` [Section titled “documentId”](#documentid) A string used as the document’s id, instead of a hash of its content. It becomes `document.id` and is part of every chunk id. Use a value that identifies the document in your system and doesn’t change when the document is edited, such as its path or database key: ```ts const result = await chunkDocument( { path: "policies/returns.md" }, { documentId: "policies/returns.md" }, ); ``` See [Ids and re-indexing](#ids-and-re-indexing) for when you need it. ### `headingPrefix` [Section titled “headingPrefix”](#headingprefix) When `true`, each chunk’s text starts with its heading path, such as `Returns policy > Refunds`, followed by a blank line. The default is `false`. The prefix counts toward the size limit. [How it works](../../how-it-works/#adding-the-heading-path-to-the-text) shows an example. ### `signal` [Section titled “signal”](#signal) An `AbortSignal` that stops chunking. When the signal is aborted, `chunkDocument` throws a `DocchunkError` with the code `ABORTED`. To give up on a slow document after 30 seconds: ```ts import { chunkDocument, DocchunkError } from "docchunk"; try { const result = await chunkDocument( { path: "large-report.pdf" }, { signal: AbortSignal.timeout(30_000) }, ); } catch (error) { if (error instanceof DocchunkError && error.code === "ABORTED") { console.log("Chunking took too long"); } } ``` Doc-chunk checks the signal between steps: before reading the source, after conversion, and after splitting. A step that has already started, such as converting a PDF, finishes before the abort takes effect. ## Ids and re-indexing [Section titled “Ids and re-indexing”](#ids-and-re-indexing) Every chunk has an `id` and a `contentHash`: * `id` is built from the document’s id, the options that affect chunking, and the chunk’s position. The same document with the same options always gives the same ids. * `contentHash` depends only on the chunk’s `text`. Use `contentHash` to find out which chunks changed since you last indexed a document, and embed only those: ```ts import { chunkDocument } from "docchunk"; const version1 = `# Returns policy You can return most items within 30 days of delivery. ## Start a return Sign in, open **Orders**, and choose the item you want to return. ## Refunds We refund the original payment method within 5 business days.`; // The same document after an edit to the Refunds section. const version2 = version1.replace("5 business days", "3 business days"); const options = { documentId: "returns-policy" }; const before = await chunkDocument( { content: version1, format: "markdown" }, options, ); const after = await chunkDocument( { content: version2, format: "markdown" }, options, ); const storedHashes = new Set(before.chunks.map((chunk) => chunk.contentHash)); const changed = after.chunks.filter((chunk) => !storedHashes.has(chunk.contentHash)); console.log(`${changed.length} of ${after.chunks.length} chunks changed`); for (const chunk of changed) { console.log(chunk.headingPath); } ``` ```txt 1 of 3 chunks changed [ 'Returns policy', 'Refunds' ] ``` In a real pipeline, `storedHashes` comes from your vector database. A typical update looks like this: 1. Chunk the new version of the document. 2. Embed the chunks whose `contentHash` isn’t stored yet. Reuse the stored embeddings for the others. 3. Replace the document’s old rows with the new chunks. ### When to pass `documentId` [Section titled “When to pass documentId”](#when-to-pass-documentid) Without `documentId`, the document’s id is a hash of its content. That has two effects: * Any edit to the document changes the id of every chunk. `contentHash` still tells you which chunks really changed. * Two files with the same content get the same chunk ids. If you store both, their rows collide. Pass a `documentId` that is unique to each document, such as its path, when you store chunks from many documents in one place or want ids that survive edits. With a fixed `documentId`, a chunk keeps its id as long as its position in the document doesn’t change. ## Warnings [Section titled “Warnings”](#warnings-1) Warnings describe problems that didn’t stop chunking. Each one has a `code`, a `message`, and, when it’s about one chunk, a `chunkIndex`. | Code | When | What to do | | ----------------- | ------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------- | | `EMPTY_DOCUMENT` | The document has no text. There are no chunks. | Check the source. It may be empty, or contain only images. | | `NO_TEXT_LAYER` | The PDF has no text layer, usually because it’s scanned. There are no chunks. | Run OCR first, then chunk the text. | | `OVERSIZED_BLOCK` | A table row, list item, code line, or word was longer than `size`, and was cut at the size limit. | Usually nothing. Raise `size` if the cut pieces are too small to be useful. | | `LARGE_CHUNK` | A strategy with no size limit produced a chunk of more than 8,000 characters. | Set `size` to split large sections or paragraphs. | Warnings are returned, not logged. Check them after each call: ```ts import { chunkDocument } from "docchunk"; const url = "https://example.com/" + "a".repeat(120); const { warnings } = await chunkDocument( { content: `See ${url} for details.`, format: "markdown" }, { size: 100, minSize: 50 }, ); for (const warning of warnings) { console.log(warning.code, warning.chunkIndex, warning.message); } ``` ```txt OVERSIZED_BLOCK 1 Chunk 1 is a hard cut of a row, item, line, or word longer than size. OVERSIZED_BLOCK 2 Chunk 2 is a hard cut of a row, item, line, or word longer than size. ``` The URL is one 140-character word, longer than the 100-character `size`, so it was cut into two chunks. ## Errors [Section titled “Errors”](#errors) When `chunkDocument` can’t produce a result, it throws a `DocchunkError`. The error’s `code` tells you what went wrong, and `message` gives the details: | Code | Thrown when | | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | | `INVALID_OPTIONS` | An option has the wrong type or value, an option isn’t accepted by the chosen strategy, or the source isn’t one of the three shapes. | | `UNSUPPORTED_FORMAT` | The format isn’t supported, or can’t be detected. | | `FILE_NOT_FOUND` | The file at `path` doesn’t exist, is a folder, or can’t be read. | | `CONVERSION_FAILED` | anydoc couldn’t convert the file, for example because it’s damaged, or because anydoc isn’t available on this platform. | | `ABORTED` | The `signal` was aborted. | Options are checked before the document is read, so an `INVALID_OPTIONS` error comes back immediately. The one exception is `headingPrefix`: if a document’s heading paths are so long that no text would fit within `size`, the error comes after the document is read. ```ts import { chunkDocument, DocchunkError } from "docchunk"; try { await chunkDocument({ path: "missing.pdf" }); } catch (error) { if (error instanceof DocchunkError) { console.log(error.code); console.log(error.message); } } ``` ```txt FILE_NOT_FOUND File not found: missing.pdf ``` Messages name the option or file at fault. Some examples: ```txt Unknown option "windowSize" for strategy "structure". Option "overlapChars" must be less than "size" (500), got 600. The document's format could not be detected from its content or file name. Pass `format` to name it. ``` When an error has an underlying cause, such as the file system error for `FILE_NOT_FOUND` or anydoc’s error for `CONVERSION_FAILED`, it’s available as `error.cause`. ## Next steps [Section titled “Next steps”](#next-steps) * [Chunk many documents](../chunk-documents/): chunk a list of files with one call. * [Strategies](../../strategies/): choose how documents are split. # Chunk many documents > Chunk a list of documents with shared options, a concurrency limit, and per-document errors. `chunkDocuments` chunks a list of documents with the same options. It runs a few documents at a time, and a document that fails doesn’t stop the others. ```ts import { chunkDocuments } from "docchunk"; const results = await chunkDocuments(sources, options); ``` The sources are the same objects [`chunkDocument`](../chunk-document/#sources) accepts, and the options are the same too, plus `concurrency`. ## Chunk a list of documents [Section titled “Chunk a list of documents”](#chunk-a-list-of-documents) ```ts import { chunkDocuments } from "docchunk"; const results = await chunkDocuments( [ { content: "# Leave\n\nYou get 25 days of paid leave.", format: "markdown" }, { path: "missing.docx" }, { content: "Office hours are 9 to 5.", format: "text" }, ], { size: 1000 }, ); for (const item of results) { if (item.ok) { console.log("ok", item.result.chunks.length); } else { console.log(`source ${item.sourceIndex} failed: ${item.error.code}`); } } ``` ```txt ok 1 source 1 failed: FILE_NOT_FOUND ok 1 ``` ## Read the results [Section titled “Read the results”](#read-the-results) `chunkDocuments` returns one item per source, in the same order as the sources, whatever order the documents finish in. Each item is one of two shapes: | Shape | Meaning | | ----------------------------------- | -------------------------------------------------------------------------------------------------------------------------- | | `{ ok: true, result }` | The document was chunked. `result` is the same object [`chunkDocument`](../chunk-document/#the-result) returns. | | `{ ok: false, error, sourceIndex }` | The document failed. `error` is a `DocchunkError`, and `sourceIndex` is the position of the source in the list you passed. | Check `item.ok` before you read `result` or `error`. In TypeScript, the check also narrows the type, so `item.result` is only available after it. A failed document doesn’t stop the batch. Every error has a `code`: if something unexpected goes wrong inside Doc-chunk, the error is wrapped in a `DocchunkError` with the code `CONVERSION_FAILED`, and the original error is in `error.cause`. To know which file each result came from, keep your list of sources and use the item’s position. For path sources, `result.document.sourcePath` also holds the path. ## Options [Section titled “Options”](#options) The options apply to every document in the list. They’re checked once, before any document is read, so a wrong option throws immediately instead of failing every document: ```ts await chunkDocuments(sources, { size: -1 }); // Throws DocchunkError INVALID_OPTIONS: // Option "size" must be a positive integer, got -1. ``` `chunkDocuments` also throws, instead of returning items, when `sources` isn’t an array or when the batch is [cancelled](#cancel-a-batch). An empty array returns an empty array. Two of the shared options need care in a batch: * **`metadata`** is copied onto the chunks of every document. For values that differ per document, such as the file name, add them when you store the chunks. * **`documentId`** would give every document the same id, so chunks at the same position in different documents would get the same chunk id. Don’t pass it to `chunkDocuments`. If you need your own id for each document, call `chunkDocument` for each one, as shown in [Documents that need different options](#documents-that-need-different-options). ## Concurrency [Section titled “Concurrency”](#concurrency) `concurrency` sets how many documents are chunked at the same time. The default is 4, and the value must be a positive whole number: ```ts const results = await chunkDocuments(sources, { concurrency: 8 }); ``` Reading files and converting PDFs and Office files happen off the main JavaScript thread, so several of them can run in parallel. Parsing and splitting the Markdown happen on the main thread, one document at a time. As a result: * A higher `concurrency` can speed up batches of PDFs and Office files. On Node.js, conversions share libuv’s thread pool, which has 4 threads unless you set the `UV_THREADPOOL_SIZE` environment variable. * For Markdown and text files, which need no conversion, `concurrency` makes little difference. * Each document in progress holds its own memory, so a higher `concurrency` uses more memory. See [Large files](#large-files). ## Cancel a batch [Section titled “Cancel a batch”](#cancel-a-batch) Pass an `AbortSignal` as `signal` to stop a batch. When the signal is aborted, `chunkDocuments` stops starting new documents and throws a `DocchunkError` with the code `ABORTED`. The results of documents that already finished are not returned. ```ts import { chunkDocuments, DocchunkError } from "docchunk"; try { const results = await chunkDocuments( sources, { signal: AbortSignal.timeout(60_000) }, ); } catch (error) { if (error instanceof DocchunkError && error.code === "ABORTED") { console.log("The batch took longer than a minute"); } } ``` The signal is checked before each document, and between the steps of each document. A step that has already started, such as converting a PDF, finishes first. Before each document, the batch also lets pending timers run, so `AbortSignal.timeout` works even when every source is a string in memory. ## Chunk every file in a folder [Section titled “Chunk every file in a folder”](#chunk-every-file-in-a-folder) This example finds the supported files in a folder and its subfolders, and chunks them in one batch: ```ts import { readdir } from "node:fs/promises"; import { extname, join } from "node:path"; import { chunkDocuments } from "docchunk"; const folder = "documents"; const extensions = new Set([".pdf", ".docx", ".pptx", ".xlsx", ".md", ".txt"]); const entries = await readdir(folder, { recursive: true, withFileTypes: true }); const paths: string[] = []; for (const entry of entries) { if (entry.isFile() && extensions.has(extname(entry.name).toLowerCase())) { paths.push(join(entry.parentPath, entry.name)); } } const results = await chunkDocuments(paths.map((path) => ({ path }))); for (const [index, item] of results.entries()) { if (item.ok) { console.log(paths[index], item.result.chunks.length); } else { console.error(paths[index], item.error.message); } } ``` Add the extensions of any other [formats](../chunk-document/#formats) you need. ## Documents that need different options [Section titled “Documents that need different options”](#documents-that-need-different-options) `chunkDocuments` uses one set of options for the whole list. When documents need different strategies, sizes, or a `documentId` each, call `chunkDocument` for each one. To keep the same one-failure-doesn’t-stop-the-others behavior, catch errors per document: ```ts import { chunkDocument } from "docchunk"; const paths = ["guides/setup.md", "guides/billing.md"]; for (const path of paths) { try { const result = await chunkDocument( { path }, { documentId: path, metadata: { source: path } }, ); console.log(path, result.chunks.length); } catch (error) { console.error(path, error); } } ``` This runs one document at a time. For a large list, you can run several of these calls at once with a concurrency library such as `p-limit`. ## Large files [Section titled “Large files”](#large-files) Parsing is the most memory-intensive step. While a document is being parsed, it uses about 250 times the size of its Markdown: roughly 250 MB for 1 MB of text. With the default `concurrency` of 4, four large documents can be in progress at the same time. If your batch includes large files, or your process has a memory limit, lower `concurrency`: ```ts const results = await chunkDocuments(sources, { concurrency: 1 }); ``` [Performance](../../performance/) has measured times and memory use. ## Next steps [Section titled “Next steps”](#next-steps) * [Chunk a document](../chunk-document/): sources, formats, the result, warnings, and errors. * [Strategies](../../strategies/): choose how documents are split.