notion-to-md

repository·master·Indexed 23 days ago

https://github.com/souvikinator/notion-to-md

A Node.js package (v3.1.9) that converts Notion pages, blocks, and lists of blocks into Markdown format with support for nesting. It provides the NotionToMarkdown class for converting content via the @notionhq/client, supports custom transformers for specific block types, and includes configuration options for child page parsing and Base64 image conversion.

Tokens
3.3K
Snippets
8
Records
22
Agent score
83%

What's inside notion-to-md

  1. Configure child page parsing behavior

    master

    You can control how child pages are handled via the config object passed to the NotionToMarkdown constructor.

    • separateChildPage: If set to true, toMarkdownString returns an object where the main content is in the parent property and child page contents are included as separate properties in the same object. (Default: false)
    • parseChildPages: If set to false, child pages will not be parsed. (Default: true)
  2. Initialize NotionToMarkdown

    master

    To use the library, instantiate the NotionToMarkdown class by passing a NotionToMarkdownOptions object. You must provide an instance of the @notionhq/client Client.

    Available configuration options in config:

    • separateChildPage (boolean, default: false): If true, child pages are returned as separate entries in the resulting Markdown object. If false, the child page title is rendered as a heading within the parent's content.
    • convertImagesToBase64 (boolean, default: false): Whether to convert images to Base64 strings.
    • parseChildPages (boolean, default: true): Whether to parse the content of child pages.
  3. Convert a Notion page to a Markdown string

    master

    To convert a full Notion page to a Markdown string, use pageToMarkdown to fetch the blocks and then toMarkdownString to convert those blocks into a string.

    Note: Since v2.7.0, toMarkdownString returns an object containing the markdown content of child pages rather than just a single string. Use the .parent property to access the main page content.

    const { Client } = require("@notionhq/client");
    const { NotionToMarkdown } = require("notion-to-md");
    
    const notion = new Client({
      auth: "your integration token",
    });
    
    const n2m = new NotionToMarkdown({ notionClient: notion });
    
    (async () => {
      const mdblocks = await n2m.pageToMarkdown("target_page_id");
      const mdString = n2m.toMarkdownString(mdblocks);
      console.log(mdString.parent);
    })();
  4. Convert a Notion page to a Markdown object

    master

    Use pageToMarkdown to convert a Notion page into a structured Markdown object (a list of blocks with nesting). The second argument allows you to specify the depth or a limit (e.g., 2).

    const { Client } = require("@notionhq/client");
    const { NotionToMarkdown } = require("notion-to-md");
    
    const notion = new Client({
      auth: "your integration token",
    });
    
    const n2m = new NotionToMarkdown({ notionClient: notion });
    
    (async () => {
      // The second argument specifies depth/limit
      const x = await n2m.pageToMarkdown("target_page_id", 2);
      console.log(x);
    })();
  5. Convert a single block to a Markdown string

    master

    Use blockToMarkdown to convert a single Notion block into its corresponding Markdown string. Note that nesting is ignored when using this method.

    const { NotionToMarkdown } = require("notion-to-md");
    
    const n2m = new NotionToMarkdown({ notionClient: notion });
    
    const result = n2m.blockToMarkdown(block);
    console.log(result);
  6. Implement Custom Transformers

    master

    You can override how specific Notion block types are parsed by using setCustomTransformer(type, func).

    • The type is the Notion block type (e.g., 'embed').
    • The func is an async function that receives the block and returns a string.
    • Important: Only the last function set for a specific type will be used.
    • To fall back to the default parsing logic within a custom transformer, return false.
    const { NotionToMarkdown } = require("notion-to-md");
    const n2m = new NotionToMarkdown({ notionClient: notion });
    
    n2m.setCustomTransformer("embed", async (block) => {
      const { embed } = block as any;
      if (!embed?.url) return "";
      
      // Custom HTML rendering for embeds
      return `<figure>
      <iframe src="${embed?.url}"></iframe>
      <figcaption>${await n2m.blockToMarkdown(embed?.caption)}</figcaption>
    </figure>`;
    });
    
    // Example of conditional fallback to default behavior
    n2m.setCustomTransformer("embed", async (block) => {
      const { embed } = block as any;
      if (embed?.url?.includes("myspecialurl.com")) {
        return `...`; // custom rendering
      }
      return false; // use default behavior
    });
    
    const result = n2m.blockToMarkdown(block);
  7. Convert a list of blocks to a Markdown object

    master

    If you already have a list of blocks (for example, retrieved via notion.blocks.children.list), you can convert them directly using blocksToMarkdown.

    const { Client } = require("@notionhq/client");
    const { NotionToMarkdown } = require("notion-to-md");
    
    const notion = new Client({
      auth: "your integration token",
    });
    
    const n2m = new NotionToMarkdown({ notionClient: notion });
    
    (async () => {
      const { results } = await notion.blocks.children.list({
        block_id,
      });
    
      const x = await n2m.blocksToMarkdown(results);
      console.log(x);
    })();
  8. Configure conversion behavior with ConfigurationOptions

    master

    The ConfigurationOptions object allows you to fine-tune how Notion blocks are converted to Markdown:

    • separateChildPage (boolean, optional): If true, child pages are handled as separate entities.
    • convertImagesToBase64 (boolean, optional): If true, images are converted to Base64 strings.
    • parseChildPages (boolean, optional): If true, the converter will attempt to parse the content of child pages.
    export type ConfigurationOptions = {
      separateChildPage?: boolean;
      convertImagesToBase64?: boolean;
      parseChildPages?: boolean;
    };
  9. Configure NotionToMarkdownOptions

    master
    When initializing the conversion process, you must provide a NotionToMarkdownOptions object. This object requires a notionClient (an instance of the @notionhq/client Client) and accepts an optional config object of type ConfigurationOptions to control conversion behavior.
  10. Convert Markdown blocks to a Markdown string

    master

    Once you have an array of MdBlock objects (e.g., from pageToMarkdown), use toMarkdownString(mdBlocks, pageIdentifier?, nestingLevel?) to convert them into a human-readable Markdown string.

    • mdBlocks: The array of MdBlock objects to convert.
    • pageIdentifier: (Optional) A key used in the returned MdStringObject to identify the content of a specific page. Defaults to "parent".
    • nestingLevel: (Optional) Defines the maximum depth of nesting for indentation. Defaults to 0.

    The method returns an MdStringObject, which is a mapping of page identifiers to their respective Markdown strings. If separateChildPage was enabled in the configuration, this object will contain entries for the parent and all child pages.