Loading and Chunking Documents

Read Markdown documents with Node.js, split text into paragraphs, and preserve a heading and source for each chunk.

🎯 Introduction

In the previous lesson, we built a RAG question-answering program using three short passages. Real source material might be a long product manual: retrieving the entire document makes it difficult to return only the parts relevant to a question.

Before generating embeddings, we therefore usually divide documents into smaller chunks. In this lesson, we will read a simple Markdown file, split it into paragraphs, and preserve its section headings and source information.


🧱 Why Split Documents into Chunks?

Suppose a membership guide covers refunds, shipping, and after-sales support. When a user asks about the refund window, the program needs the refund policy, rather than the entire guide.

Length is not the only consideration. For example, a policy might say, “You can request a refund within 7 days of purchase. Sale items are nonrefundable.” Splitting between these sentences could leave a retrieval result with only the first sentence, omitting an important restriction.

Common chunking approaches include:

ApproachCharacteristicsCommon uses
Fixed lengthMakes chunk size easy to control, but can split a complete thoughtPlain text with little structure
Headings and paragraphsPreserves the original structure and meaning where possibleMarkdown and technical documentation
Overlapping chunksRepeats some content between adjacent chunks to reduce information loss at boundariesSplitting longer passages further

We will start with the simplest approach: split by paragraph and keep the associated heading. We do not need to implement the other approaches yet.


🛠 Read a Markdown Document

Create guide.md with the following content:

# Membership Guide

## Refunds

You can request a refund within 7 days of purchase. Sale items are nonrefundable.

## Shipping

Standard orders ship within 48 hours of payment.

Use the built-in file API in Node.js 24.x; no additional dependencies are needed. Create 03.chunk.mjs in the same directory:

import { readFile } from "node:fs/promises";

const raw = await readFile("guide.md", "utf8");
const paragraphs = raw
    .split(/\n\s*\n/)
    .map((part) => part.trim())
    .filter(Boolean);

console.log(JSON.stringify(paragraphs, null, 4));

Here, split(/\n\s*\n/) splits on blank lines, trim() removes whitespace from either end of each paragraph, and filter(Boolean) removes empty entries. Run:

node 03.chunk.mjs

The output is:

[
    "# Membership Guide",
    "## Refunds",
    "You can request a refund within 7 days of purchase. Sale items are nonrefundable.",
    "## Shipping",
    "Standard orders ship within 48 hours of payment."
]

Notice that headings are separate paragraphs too. If we retrieve these paragraphs as they are, the refund policy will not include its “Refunds” section heading. Let’s address that next.


🧩 Preserve a Heading and Source for Each Chunk

In the same 03.chunk.mjs file, keep the code that reads the file and creates paragraphs, then replace the final console.log(...) with:

const chunks = [];
let heading = "";

for (const paragraph of paragraphs) {
    if (/^#{1,6}\s+/.test(paragraph)) {
        heading = paragraph.replace(/^#{1,6}\s+/, "");
        continue;
    }

    chunks.push({
        text: `${heading}\n${paragraph}`,
        source: "guide.md",
        heading
    });
}

console.log(JSON.stringify(chunks, null, 4));

This code does two main things:

  1. When it encounters a Markdown heading, it records the current heading without creating a separate chunk for it.
  2. When it encounters a body paragraph, it creates a chunk, includes the most recent heading in text, and also saves heading and the filename as source.

Run node 03.chunk.mjs again. The output is:

[
    {
        "text": "Refunds\nYou can request a refund within 7 days of purchase. Sale items are nonrefundable.",
        "source": "guide.md",
        "heading": "Refunds"
    },
    {
        "text": "Shipping\nStandard orders ship within 48 hours of payment.",
        "source": "guide.md",
        "heading": "Shipping"
    }
]

Each body paragraph is now a chunk with a heading. You can pass text to an embedding model to generate a vector, then use source and heading to show users where a retrieved chunk came from.

Including the heading in text preserves some context for retrieval. The separate heading and source fields store source metadata for display later.

This code only demonstrates simple Markdown. It records only the most recent heading, rather than the full hierarchy such as “Membership Guide → Refunds.” Splitting on blank lines also cannot reliably handle code blocks, tables, lists, or complex heading structures. Use a parser that understands Markdown structure when processing complex documents.

❓ Knowledge Check

Q: Why should a chunk include source information as well as its text?

Retrieval needs to identify both relevant text and the file and section it came from. This lets the application provide verifiable sources when generating an answer, rather than returning an answer with no attribution.


🧪 Exercise

Add a ## After-Sales Support section to the end of guide.md, with two body paragraphs separated by a blank line. Run 03.chunk.mjs and inspect the resulting chunks.

Success criteria: The output contains two additional chunks, both with heading set to After-Sales Support and source set to guide.md. The ## After-Sales Support heading does not become a separate chunk.


🎉 Congratulations! You can now read and split simple Markdown documents while preserving each chunk’s heading and source.