### Example: Read EPUB from GitHub Release using npx Source: https://github.com/julien-c/epub/blob/master/_autodocs/api-reference/cli.md Shows how to use npx to execute the EPUB CLI for reading a book from a GitHub release without prior installation. ```bash $ npx epub https://github.com/progit/progit2/releases/download/v1.0/book.epub ``` -------------------------------- ### EPub Image Root Examples Source: https://github.com/julien-c/epub/blob/master/_autodocs/configuration.md Examples demonstrating different configurations for the image root URL prefix. ```typescript new EPub("book.epub", "/images/") // Default ``` ```typescript new EPub("book.epub", "/static/images/") // Custom path ``` ```typescript new EPub("book.epub", "images") // "images/" after normalization ``` ```typescript new EPub("book.epub", "https://cdn.example.com/images/") // Full URL ``` -------------------------------- ### EPub Link Root Examples Source: https://github.com/julien-c/epub/blob/master/_autodocs/configuration.md Examples demonstrating different configurations for the link root URL prefix. ```typescript new EPub("book.epub", undefined, "/links/") // Default ``` ```typescript new EPub("book.epub", undefined, "/chapters/") // Custom path ``` ```typescript new EPub("book.epub", undefined, "chapters") // "chapters/" after normalization ``` -------------------------------- ### Install EPUB CLI Source: https://github.com/julien-c/epub/blob/master/_autodocs/api-reference/cli.md Install the EPUB CLI globally using npm or use npx for immediate execution without installation. ```bash npm install -g epub # or with npx (no installation required) npx epub ``` -------------------------------- ### EPub Constructor Examples Source: https://github.com/julien-c/epub/blob/master/_autodocs/api-reference/EPub.md Demonstrates creating an EPub instance from a file path, Buffer, ArrayBuffer, or with custom URL prefixes for images and links. ```typescript import EPub from "epub"; // From file path const epub = new EPub("./book.epub"); // From Buffer const fileBuffer = await fs.promises.readFile("./book.epub"); const epub = new EPub(fileBuffer); // From ArrayBuffer (e.g., from fetch) const response = await fetch("https://example.com/book.epub"); const arrayBuffer = await response.arrayBuffer(); const epub = new EPub(arrayBuffer); // With custom URL prefixes const epub = new EPub("./book.epub", "/static/images/", "/static/chapters/"); ``` -------------------------------- ### Install EPUB Module Source: https://github.com/julien-c/epub/blob/master/README.md Install the EPUB module using npm for use in your Node.js project. ```bash npm install epub ``` -------------------------------- ### Install EPub Module Source: https://github.com/julien-c/epub/blob/master/_autodocs/getting-started.md Install the epub module using npm. Ensure you have Node.js 22.6.0 or higher and TypeScript support. ```bash npm install epub ``` -------------------------------- ### Example: Extract and Process EPUB Content Source: https://github.com/julien-c/epub/blob/master/_autodocs/api-reference/cli.md Provides examples of extracting EPUB content to a text file and then using standard Unix tools to view or search within the extracted text. ```bash $ epub ./book.epub > book.txt $ head -100 book.txt # View first 100 lines $ grep -n "keyword" book.txt # Search for keyword ``` -------------------------------- ### Metadata Output Example Source: https://github.com/julien-c/epub/blob/master/_autodocs/api-reference/cli.md Illustrates the format and fields of the metadata section output by the EPUB CLI. ```text Metadata: title: Alice's Adventures in Wonderland creator: Lewis Carroll language: en subject: Fantasy date: 2006-08-12 description: A classic children's novel publisher: Project Gutenberg ``` -------------------------------- ### File Organization Structure Source: https://github.com/julien-c/epub/blob/master/_autodocs/README.md Illustrates the directory structure of the EPUB project, outlining the location of API references, type definitions, error documentation, configuration, architecture, getting started guides, and examples. ```tree /api-reference/ ├── EPub.md # Main EPub class reference ├── cli.md # CLI usage guide └── helpers.md # Helper functions ├── types.md # Type definitions ├── errors.md # Error reference ├── configuration.md # Configuration options ├── architecture.md # Design and structure ├── getting-started.md # Quick start guide └── examples.md # Working examples ``` -------------------------------- ### Node.js Express EPUB Server Setup Source: https://github.com/julien-c/epub/blob/master/_autodocs/examples.md Initializes an Express server to load and serve EPUB content. Requires the 'epub' and 'express' packages. The EPUB is loaded once on server startup. ```typescript import express from "express"; import EPub from "epub"; const app = express(); const epubPath = "./books/sample.epub"; let epub: EPub | null = null; // Initialize EPUB on startup app.use(async (req, res, next) => { if (!epub) { try { epub = new EPub(epubPath); await epub.parse(); console.log(`Loaded: ${epub.metadata.title}`); } catch (err) { return res.status(500).json({ error: "Failed to load EPUB" }); } } next(); }); // Metadata endpoint app.get("/api/book/metadata", (req, res) => { res.json({ title: epub!.metadata.title, author: epub!.metadata.creator, description: epub!.metadata.description, language: epub!.metadata.language, chapters: epub!.flow.length, }); }); // Table of contents endpoint app.get("/api/book/toc", (req, res) => { res.json(epub!.toc); }); // Chapter content endpoint app.get("/api/book/chapters/:id", async (req, res) => { try { const { id } = req.params; if (!epub!.manifest[id]) { return res.status(404).json({ error: "Chapter not found" }); } const html = await epub!.getChapter(id); res.json({ id, content: html }); } catch (err) { res.status(400).json({ error: (err as Error).message }); } }); // Image endpoint app.get("/api/book/images/:id", async (req, res) => { try { const { id } = req.params; if (!epub!.manifest[id]) { return res.status(404).json({ error: "Image not found" }); } const { data, mimeType } = await epub!.getImage(id); res.setHeader("Content-Type", mimeType); res.send(data); } catch (err) { res.status(400).json({ error: (err as Error).message }); } }); app.listen(3000, () => { console.log("EPUB reader running on http://localhost:3000"); }); ``` -------------------------------- ### Manifest Path Resolution Example Source: https://github.com/julien-c/epub/blob/master/_autodocs/architecture.md Illustrates how manifest paths are resolved relative to the package.opf directory to ensure they are absolute within the ZIP archive. ```plaintext // package.opf is at OEBPS/package.opf // Manifest href is "ch01.xhtml" // Resolved path becomes "OEBPS/ch01.xhtml" ``` -------------------------------- ### Example: Save EPUB Contents to Text File Source: https://github.com/julien-c/epub/blob/master/_autodocs/api-reference/cli.md Demonstrates how to redirect the full text content of an EPUB file to a local text file. ```bash $ epub ./book.epub > book-text.txt ``` -------------------------------- ### Example: Pipe EPUB Output to Less for Paging Source: https://github.com/julien-c/epub/blob/master/_autodocs/api-reference/cli.md Illustrates piping the output of the EPUB CLI to the 'less' command for interactive viewing of large EPUB contents. ```bash $ epub ./book.epub | less ``` -------------------------------- ### Accessing Book Metadata Source: https://github.com/julien-c/epub/blob/master/_autodocs/types.md Example of how to instantiate the EPub class, parse a book, and access its metadata properties like title and creator. ```typescript const epub = new EPub("book.epub"); await epub.parse(); console.log(epub.metadata.title); console.log(epub.metadata.creator); console.log(epub.metadata.subjects); ``` -------------------------------- ### URL Rewriting Example Source: https://github.com/julien-c/epub/blob/master/_autodocs/getting-started.md Demonstrates how URLs within the EPUB's HTML content are rewritten based on the configured prefixes when calling `getChapter()`. ```typescript // Original: // After: // Original: // After: ``` -------------------------------- ### Rewritten Image URL Example Source: https://github.com/julien-c/epub/blob/master/_autodocs/configuration.md Illustrates the format of a rewritten image URL using the default imageroot and item ID. ```html ``` -------------------------------- ### Table of Contents Output Example Source: https://github.com/julien-c/epub/blob/master/_autodocs/api-reference/cli.md Shows the hierarchical structure of the Table of Contents as displayed by the EPUB CLI, using indentation to denote nesting levels. ```text Table of Contents: Chapter One Section One Subsection A Chapter Two ``` -------------------------------- ### Parse EPUB and Get Metadata/Chapter Source: https://github.com/julien-c/epub/blob/master/_autodocs/README.md Instantiate the EPub class, parse the file, and access book metadata and chapter content. Ensure the file path is correct. ```typescript import EPub from "epub"; const epub = new EPub("./book.epub"); await epub.parse(); console.log(epub.metadata.title); const html = await epub.getChapter(epub.flow[0].id); ``` -------------------------------- ### EPUB TOC Structure Example Source: https://github.com/julien-c/epub/blob/master/_autodocs/architecture.md Shows the hierarchical structure of a Table of Contents (TOC) in an EPUB's toc.ncx file, including nested navigation points. ```xml Chapter 1 Section 1.1 ``` -------------------------------- ### Build Reading Progress Tracker Source: https://github.com/julien-c/epub/blob/master/_autodocs/examples.md An example of creating a reading progress tracker that saves metadata like title, author, and current chapter progress to a JSON file. It simulates reading through chapters and handles potential errors for non-readable chapters. ```typescript import EPub from "epub"; import fs from "node:fs/promises"; const epub = new EPub("./book.epub"); await epub.parse(); // Save metadata const metadata = { title: epub.metadata.title, author: epub.metadata.creator, totalChapters: epub.flow.length, startedAt: new Date().toISOString(), currentChapter: 0, progress: 0, bookmarks: [], }; await fs.writeFile("reading.json", JSON.stringify(metadata, null, 2)); // Simulate reading for (let i = 0; i < epub.flow.length; i++) { const chapter = epub.flow[i]; try { const text = await epub.getChapter(chapter.id); metadata.currentChapter = i; metadata.progress = ((i + 1) / epub.flow.length) * 100; console.log(`Chapter ${i + 1}/${epub.flow.length} - ${chapter.id}`); } catch { console.error(`Skipped non-readable chapter: ${chapter.id}`); } } metadata.completedAt = new Date().toISOString(); await fs.writeFile("reading.json", JSON.stringify(metadata, null, 2)); ``` -------------------------------- ### Rewritten Link URL Example Source: https://github.com/julien-c/epub/blob/master/_autodocs/configuration.md Illustrates the format of a rewritten link URL using the default linkroot, item ID, and preserving anchors. ```html ``` -------------------------------- ### Get Images from EPUB Source: https://github.com/julien-c/epub/blob/master/_autodocs/getting-started.md Find and retrieve the cover image from an EPUB file, then save it to disk. Requires Node.js 'fs/promises' for file writing. ```typescript const epub = new EPub("./book.epub"); await epub.parse(); // Find cover image const coverItem = Object.values(epub.manifest).find(item => item["media-type"]?.startsWith("image/") ); if (coverItem) { const { data, mimeType } = await epub.getImage(coverItem.id); // Save to disk import fs from "node:fs/promises"; const ext = mimeType.split("/")[1]; // "jpeg" from "image/jpeg" await fs.writeFile(`cover.${ext}`, data); } ``` -------------------------------- ### Iterating and Filtering Table of Contents Source: https://github.com/julien-c/epub/blob/master/_autodocs/types.md Example of how to traverse the table of contents, display entries with indentation based on their level, and filter entries by level to get chapters or sections. ```typescript const epub = new EPub("book.epub"); await epub.parse(); // Iterate TOC with indentation for (const entry of epub.toc) { const indent = " ".repeat(entry.level); console.log(`${indent}${entry.title}`); console.log(` ${indent}-> ${entry.href} (id: ${entry.id})`); console.log(` ${indent}-> order: ${entry.order}`); } // Filter by level const chapters = epub.toc.filter(e => e.level === 0); const sections = epub.toc.filter(e => e.level === 1); ``` -------------------------------- ### Configure EPub for Development vs. Production Source: https://github.com/julien-c/epub/blob/master/_autodocs/configuration.md Demonstrates setting up EPub configuration for different environments. Use static paths for development and CDN URLs for production. ```typescript // Development const epub = new EPub(filePath, "/images/", "/chapters/"); // Production with CDN const epub = new EPub(filePath, process.env.CDN_URL + "/images/", "/api/chapters/"); ``` -------------------------------- ### Use from CLI Source: https://github.com/julien-c/epub/blob/master/_autodocs/README.md Execute the EPUB library directly from the command line interface, providing a local file path or a URL to an EPUB file. ```bash npx epub ./book.epub ``` ```bash npx epub https://example.com/book.epub ``` -------------------------------- ### Load EPUB from File Path Source: https://github.com/julien-c/epub/blob/master/_autodocs/getting-started.md Initialize the EPub library by providing a direct path to the EPUB file. ```typescript const epub = new EPub("./alice.epub"); await epub.parse(); ``` -------------------------------- ### Initialize EPUB Parser Source: https://github.com/julien-c/epub/blob/master/README.md Import and initialize the EPub class with the path to your EPUB file. Optional parameters can configure image and chapter URL prefixes. ```javascript import EPub from "epub"; const epub = new EPub(pathToFile); ``` -------------------------------- ### Get Image Source: https://github.com/julien-c/epub/blob/master/_autodocs/examples.md Retrieves an image from the EPUB file identified by its ID. ```APIDOC ## GET /api/book/images/:id ### Description Retrieves an image from the EPUB file identified by its ID. ### Method GET ### Endpoint /api/book/images/:id ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the image. ### Request Example None ### Response #### Success Response (200) - The response body contains the image data. - The `Content-Type` header is set to the image's MIME type. #### Response Example (Binary image data) #### Error Response (404) - **error** (string) - "Image not found" #### Error Response (400) - **error** (string) - The error message if image retrieval fails. ``` -------------------------------- ### Basic CLI Syntax Source: https://github.com/julien-c/epub/blob/master/_autodocs/api-reference/cli.md The fundamental command structure for using the EPUB CLI to read EPUB files or URLs. ```bash epub ``` -------------------------------- ### Get Table of Contents Source: https://github.com/julien-c/epub/blob/master/_autodocs/examples.md Retrieves the table of contents for the loaded EPUB book. ```APIDOC ## GET /api/book/toc ### Description Retrieves the table of contents for the loaded EPUB book. ### Method GET ### Endpoint /api/book/toc ### Parameters None ### Request Example None ### Response #### Success Response (200) - An array of objects, where each object represents a table of contents entry, typically including `id`, `href`, and `label`. #### Response Example [ { "id": "toc_1", "href": "chapter1.xhtml", "label": "Chapter 1" }, { "id": "toc_2", "href": "chapter2.xhtml", "label": "Chapter 2" } ] ``` -------------------------------- ### Get Chapter Content Source: https://github.com/julien-c/epub/blob/master/_autodocs/examples.md Retrieves the HTML content of a specific chapter identified by its ID. ```APIDOC ## GET /api/book/chapters/:id ### Description Retrieves the HTML content of a specific chapter identified by its ID. ### Method GET ### Endpoint /api/book/chapters/:id ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the chapter. ### Request Example None ### Response #### Success Response (200) - **id** (string) - The identifier of the chapter. - **content** (string) - The HTML content of the chapter. #### Response Example { "id": "chapter_1", "content": "

Chapter 1

This is the content of the first chapter.

" } #### Error Response (404) - **error** (string) - "Chapter not found" #### Error Response (400) - **error** (string) - The error message if chapter retrieval fails. ``` -------------------------------- ### EPub Constructor Source: https://github.com/julien-c/epub/blob/master/_autodocs/api-reference/EPub.md Initializes a new EPub instance. It can accept the EPUB data as a file path (string), a Buffer, or an ArrayBuffer. Optional parameters allow specifying URL prefixes for images and chapter links. ```APIDOC ## EPub Constructor ### Description Creates a new EPub instance. ### Parameters #### Path Parameters - **input** (string | Buffer | ArrayBuffer) - Required - File path (string), Buffer, or ArrayBuffer containing EPUB data - **imageroot** (string) - Optional - URL prefix for image resources. Auto-appends trailing slash if missing. Defaults to `/images/`. - **linkroot** (string) - Optional - URL prefix for chapter links. Auto-appends trailing slash if missing. Defaults to `/links/`. ### Request Example ```typescript import EPub from "epub"; // From file path const epub = new EPub("./book.epub"); // From Buffer const fileBuffer = await fs.promises.readFile("./book.epub"); const epub = new EPub(fileBuffer); // From ArrayBuffer (e.g., from fetch) const response = await fetch("https://example.com/book.epub"); const arrayBuffer = await response.arrayBuffer(); const epub = new EPub(arrayBuffer); // With custom URL prefixes const epub = new EPub("./book.epub", "/static/images/", "/static/chapters/"); ``` ``` -------------------------------- ### Import EPub Library Source: https://github.com/julien-c/epub/blob/master/_autodocs/api-reference/EPub.md Demonstrates how to import the EPub library using two common module import syntaxes. ```typescript import EPub from "epub"; ``` ```typescript // or import { EPub } from "epub"; ``` -------------------------------- ### Get Book Metadata Source: https://github.com/julien-c/epub/blob/master/_autodocs/examples.md Retrieves metadata about the loaded EPUB book, including title, author, description, language, and the number of chapters. ```APIDOC ## GET /api/book/metadata ### Description Retrieves metadata about the loaded EPUB book. ### Method GET ### Endpoint /api/book/metadata ### Parameters None ### Request Example None ### Response #### Success Response (200) - **title** (string) - The title of the book. - **author** (string) - The author of the book. - **description** (string) - The description of the book. - **language** (string) - The language of the book. - **chapters** (integer) - The total number of chapters in the book. #### Response Example { "title": "Sample EPUB Title", "author": "John Doe", "description": "A sample EPUB file for testing.", "language": "en", "chapters": 10 } ``` -------------------------------- ### Get Chapter Content Source: https://github.com/julien-c/epub/blob/master/README.md Retrieve the text content of a specific chapter using its ID. The chapter ID can be obtained from the epub.flow property. ```javascript const text = await epub.getChapter("chapter_id"); ``` -------------------------------- ### Error Handling: Missing Argument Source: https://github.com/julien-c/epub/blob/master/_autodocs/api-reference/cli.md Demonstrates the CLI's response when no EPUB file or URL is provided as an argument. ```bash $ epub Usage: epub # Exit code: 1 ``` -------------------------------- ### EPub Class Usage Source: https://github.com/julien-c/epub/blob/master/_autodocs/README.md Demonstrates how to instantiate the EPub class, parse an EPUB file, and access metadata and chapter content. ```APIDOC ## EPub Class Main class for parsing and reading EPUB files. ```typescript import EPub from "epub"; const epub = new EPub("./book.epub"); await epub.parse(); console.log(epub.metadata.title); const html = await epub.getChapter(epub.flow[0].id); ``` ### Constructor ```typescript new EPub(input: string | Buffer | ArrayBuffer, imageroot?: string, linkroot?: string) ``` ### Core Methods - `parse(): Promise` — Parse EPUB file - `getChapter(id: string): Promise` — Get processed chapter HTML - `getChapterRaw(id: string): Promise` — Get raw chapter HTML - `getImage(id: string): Promise<{ data: Buffer; mimeType: string }> ` — Get image - `getFile(id: string): Promise<{ data: Buffer; mimeType: string }> ` — Get any file - `hasDRM(): boolean` — Check for DRM protection ### Key Properties - `metadata: Metadata` — Book metadata (title, author, language, etc.) - `flow: ManifestItem[]` — Reading order (chapters) - `toc: TocElement[]` — Table of contents (hierarchical) - `manifest: Record` — All resources indexed by ID - `spine: { toc, contents }` — Spine structure - `version: string` — EPUB specification version ``` -------------------------------- ### Load EPUB from Network Source: https://github.com/julien-c/epub/blob/master/_autodocs/getting-started.md Fetch an EPUB file from a URL, convert it to an ArrayBuffer, and then initialize the EPub library. ```typescript const response = await fetch("https://example.com/book.epub"); const arrayBuffer = await response.arrayBuffer(); const epub = new EPub(arrayBuffer); await epub.parse(); ``` -------------------------------- ### Load EPUB from CLI Source: https://github.com/julien-c/epub/blob/master/_autodocs/getting-started.md Use the command-line interface to load EPUB files from a local path or a remote URL. ```bash # Local file npx epub ./book.epub # Remote URL npx epub https://github.com/progit/progit2/releases/download/2.1.449/progit.epub ``` -------------------------------- ### Load EPUB from Buffer Source: https://github.com/julien-c/epub/blob/master/_autodocs/getting-started.md Load an EPUB file into memory as a buffer and then initialize the EPub library. ```typescript import fs from "node:fs/promises"; const buffer = await fs.readFile("./alice.epub"); const epub = new EPub(buffer); await epub.parse(); ``` -------------------------------- ### EPub Constructor with Buffer Source: https://github.com/julien-c/epub/blob/master/_autodocs/configuration.md Instantiate EPub using a Buffer. Use this when the file content is already loaded into memory. ```typescript import fs from "node:fs/promises"; const buffer = await fs.readFile("./book.epub"); const epub = new EPub(buffer); ``` -------------------------------- ### EPub Constructor and Parsing Source: https://github.com/julien-c/epub/blob/master/README.md Instantiate the EPub class with a file path and then parse the EPUB file to access its contents. ```APIDOC ## Constructor and Parsing ### Description Instantiate the EPub class with the path to an EPUB file and then parse the file to access its metadata and content. ### Usage ```js import EPub from "epub"; const epub = new EPub(pathToFile, imageWebRoot, chapterWebRoot); await epub.parse(); console.log(epub.metadata.title); ``` ### Parameters #### Path Parameters - **pathToFile** (string) - Required - The file path to an EPUB file. - **imageWebRoot** (string) - Optional - The prefix for image URLs. Defaults to `/images/`. - **chapterWebRoot** (string) - Optional - The prefix for chapter URLs. Defaults to `/links/`. ``` -------------------------------- ### Error Handling: File Not Found Source: https://github.com/julien-c/epub/blob/master/_autodocs/api-reference/cli.md Shows the CLI's behavior when attempting to read a non-existent local EPUB file. ```bash $ epub ./nonexistent.epub # Prints error from parser # Exit code: 1 (implicit from uncaught error) ``` -------------------------------- ### Minimal EPub Configuration Source: https://github.com/julien-c/epub/blob/master/_autodocs/configuration.md Instantiates an EPub object with only the book path, relying on default image and link roots. ```typescript const epub = new EPub("book.epub"); // Uses defaults: "/images/" and "/links/" ``` -------------------------------- ### Get Image Data Source: https://github.com/julien-c/epub/blob/master/_autodocs/api-reference/EPub.md Retrieves the raw data and MIME type for an image within the EPUB file. This method requires the EPUB to be parsed first. The image ID is obtained from the manifest. ```typescript async getImage(id: string): Promise<{ data: Buffer; mimeType: string }> ``` ```typescript const epub = new EPub("book.epub"); await epub.parse(); const { data, mimeType } = await epub.getImage("cover"); console.log(mimeType); // "image/jpeg", "image/png", etc. // Save to disk import fs from "node:fs"; await fs.promises.writeFile("cover.jpg", data); ``` -------------------------------- ### Preventing 'Invalid mime type for image' Error Source: https://github.com/julien-c/epub/blob/master/_autodocs/errors.md Demonstrates how to prevent 'Invalid mime type for image' errors by verifying that the item's 'media-type' starts with 'image/' before calling EPub.getImage(). ```typescript const id = "image1"; const item = epub.manifest[id]; if ((item["media-type"] || "").toLowerCase().startsWith("image/")) { const { data, mimeType } = await epub.getImage(id); } else { console.error("Not an image file"); } ``` -------------------------------- ### Extract Images from EPUB Source: https://github.com/julien-c/epub/blob/master/_autodocs/examples.md Use this function to extract all image assets from an EPUB file and save them to a specified directory. Ensure the 'epub' and 'node:fs/promises', 'node:path' modules are installed and imported. ```typescript import EPub from "epub"; import fs from "node:fs/promises"; import path from "node:path"; async function extractImages(epubPath: string, outputDir: string) { const epub = new EPub(epubPath); await epub.parse(); // Create output directory await fs.mkdir(outputDir, { recursive: true }); // Find and extract all images let count = 0; for (const [id, item] of Object.entries(epub.manifest)) { const mediaType = (item["media-type"] || "").toLowerCase(); if (mediaType.startsWith("image/")) { try { const { data, mimeType } = await epub.getImage(id); // Determine file extension const ext = mimeType.split("/").pop() || "bin"; const filename = `${id}.${ext}`; const filepath = path.join(outputDir, filename); await fs.writeFile(filepath, data); console.log(`Extracted: ${filename}`); count++; } catch (err) { console.error(`Failed to extract ${id}:`, err.message); } } } console.log(`Total images extracted: ${count}`); } await extractImages("./book.epub", "./images"); ``` -------------------------------- ### Get Processed Chapter HTML Source: https://github.com/julien-c/epub/blob/master/_autodocs/api-reference/EPub.md Retrieves the HTML content of a chapter with URLs rewritten for images and links. Use this for displaying chapter content in a web context. Ensure the EPUB has been parsed first. ```typescript async getChapter(id: string): Promise ``` ```typescript const epub = new EPub("book.epub"); await epub.parse(); // Get first chapter const firstChapterId = epub.flow[0].id; const html = await epub.getChapter(firstChapterId); // URLs are rewritten // becomes //
becomes ``` -------------------------------- ### Default EPub Configuration Source: https://github.com/julien-c/epub/blob/master/_autodocs/configuration.md Instantiates an EPub object using default image and link root paths. ```typescript const epub = new EPub("book.epub"); // imageroot: "/images/" // linkroot: "/links/" ``` -------------------------------- ### Maintain Consistent URL Prefixes Source: https://github.com/julien-c/epub/blob/master/_autodocs/configuration.md Illustrates consistent prefix styles for EPub configuration. Both static paths and full URLs are acceptable, but mixing styles or omitting trailing slashes should be avoided. ```typescript // Good: both are static paths new EPub(file, "/static/imgs/", "/static/chapters/"); // OK: full URLs where appropriate new EPub(file, "https://cdn.example.com/imgs/", "/api/chapters/"); // Avoid: inconsistent styles new EPub(file, "/img", "/chapter/"); // Missing trailing slashes ``` -------------------------------- ### Get Raw Chapter HTML Source: https://github.com/julien-c/epub/blob/master/_autodocs/api-reference/EPub.md Retrieves the unprocessed, raw HTML content of a chapter. Use this when you need the original file content without any URL modifications. The EPUB must be parsed prior to calling this method. ```typescript async getChapterRaw(id: string): Promise ``` ```typescript const epub = new EPub("book.epub"); await epub.parse(); const raw = await epub.getChapterRaw(epub.flow[0].id); // URLs are NOT modified, contains original file references ``` -------------------------------- ### Get File by Manifest ID - EPub Source: https://github.com/julien-c/epub/blob/master/_autodocs/api-reference/EPub.md Retrieve a file from the EPUB archive using its manifest ID. Ensure the EPUB is parsed before calling this method. The returned object contains the file's data as a Buffer and its MIME type. ```typescript const epub = new EPub("book.epub"); await epub.parse(); // Get CSS stylesheet const { data, mimeType } = await epub.getFile("style1"); console.log(mimeType); // "text/css" // Get arbitrary file const { data } = await epub.getFile("cover-image"); ``` -------------------------------- ### EPub Constructor with File Path Source: https://github.com/julien-c/epub/blob/master/_autodocs/configuration.md Instantiate EPub using a file path. The file is read asynchronously during the parse() method. ```typescript const epub = new EPub("./book.epub"); ``` -------------------------------- ### Convert EPUB to Plain Text Source: https://github.com/julien-c/epub/blob/master/_autodocs/examples.md This function converts an EPUB file into a single plain text file, preserving metadata, table of contents, and chapter content. It includes a helper function 'htmlToText' for basic HTML sanitization. Ensure 'epub' and 'node:fs/promises' modules are installed and imported. ```typescript import EPub from "epub"; import fs from "node:fs/promises"; function htmlToText(html: string): string { return html .replace(//gi, "\n") .replace(/<\/p>/gi, "\n\n") .replace(/<\/h[1-6]>/gi, "\n\n") .replace(/<\/div>/gi, "\n") .replace(/<\/li>/gi, "\n") .replace(/<[^>]+>/g, "") .replace(/&#(\d+);/g, (_m, code) => String.fromCodePoint(Number(code))) .replace(/&#x([0-9a-fA-F]+);/g, (_m, code) => String.fromCodePoint(parseInt(code, 16))) .replace(/&/g, "&") .replace(/</g, "<") .replace(/>/g, ">") .replace(/"/g, '"') .replace(/ /g, " ") .replace(/\n{3,}/g, "\n\n") .trim(); } async function epubToText(epubPath: string, outputPath: string) { const epub = new EPub(epubPath); await epub.parse(); const lines: string[] = []; // Add metadata header lines.push(`# ${epub.metadata.title}`); lines.push(`Author: ${epub.metadata.creator}`); if (epub.metadata.description) { lines.push(`\n${epub.metadata.description}`); } lines.push("\n" + "=".repeat(60) + "\n"); // Add TOC lines.push("Table of Contents:\n"); for (const entry of epub.toc) { const indent = " ".repeat(entry.level + 1); lines.push(`${indent}- ${entry.title}`); } lines.push("\n" + "=".repeat(60) + "\n\n"); // Add chapter contents for (const chapter of epub.flow) { try { const html = await epub.getChapter(chapter.id); const text = htmlToText(html); lines.push(text); lines.push("\n\n" + "-".repeat(40) + "\n\n"); } catch { // Skip non-chapter files } } await fs.writeFile(outputPath, lines.join("\n")); console.log(`Converted to: ${outputPath}`); } await epubToText("./book.epub", "./book.txt"); ``` -------------------------------- ### Read EPUB from Local File Path Source: https://github.com/julien-c/epub/blob/master/_autodocs/api-reference/cli.md Demonstrates reading an EPUB file located on the local filesystem using its relative or absolute path. ```bash # Read from local file epub ./alice.epub ``` ```bash # Read from absolute path epub /home/user/books/novel.epub ``` -------------------------------- ### EPub Constructor with Custom Image Root Source: https://github.com/julien-c/epub/blob/master/_autodocs/configuration.md Configure a custom URL prefix for image resources. The trailing slash is automatically added if missing. ```typescript const epub = new EPub("book.epub", "/static/imgs/"); await epub.parse(); await epub.getChapter("ch01"); // becomes ``` -------------------------------- ### Extract Text Content from XML Value Source: https://github.com/julien-c/epub/blob/master/_autodocs/api-reference/helpers.md Extracts trimmed text content from various XML value types including strings, numbers, objects with a '#text' property, null, or undefined. Returns an empty string for other object types. Use this to safely get string representations from parsed XML data. ```typescript function textOf(val: unknown): string textOf("Hello World") // "Hello World" textOf(" spaces ") // "spaces" textOf(123) // "123" textOf({ "#text": "content" }) // "content" textOf(null) // "" textOf({}) // "" ``` -------------------------------- ### Default URL Prefixes Source: https://github.com/julien-c/epub/blob/master/_autodocs/getting-started.md Illustrates the default URL prefixes used for rewriting image and chapter links when initializing the EPub library. ```typescript // Default prefixes const epub = new EPub("./book.epub"); // imageroot: "/images/" // linkroot: "/links/" ``` -------------------------------- ### Custom Web Paths for EPub Source: https://github.com/julien-c/epub/blob/master/_autodocs/configuration.md Instantiates an EPub object with custom web server paths for images and chapters. ```typescript const epub = new EPub("book.epub", "/public/imgs/", "/public/chapters/"); ``` -------------------------------- ### Configure fast-xml-parser for EPUB Source: https://github.com/julien-c/epub/blob/master/_autodocs/architecture.md Sets up the XML parser with specific options to handle EPUB's attribute and content structure. Attributes are prefixed with '@_' and XML declarations are ignored. ```typescript const xmlParser = new XMLParser({ ignoreAttributes: false, attributeNamePrefix: "@_", ignoreDeclaration: true, }); ``` -------------------------------- ### List All Resources in an EPUB Source: https://github.com/julien-c/epub/blob/master/_autodocs/getting-started.md Enumerate all chapters, images, and stylesheets within an EPUB file by iterating through the `flow` and `manifest` properties. This provides a comprehensive overview of the EPUB's components. ```typescript const epub = new EPub("./book.epub"); await epub.parse(); console.log("Chapters:"); for (const item of epub.flow) { console.log(` ${item.id}: ${item.href} (${item["media-type"]})`); } console.log("\nImages:"); for (const [id, item] of Object.entries(epub.manifest)) { if (item["media-type"]?.startsWith("image/")) { console.log(` ${id}: ${item.href}`); } } console.log("\nStylesheets:"); for (const [id, item] of Object.entries(epub.manifest)) { if (item["media-type"] === "text/css") { console.log(` ${id}: ${item.href}`); } } ``` -------------------------------- ### Image URL Rewriting with Default Config Source: https://github.com/julien-c/epub/blob/master/_autodocs/configuration.md Shows how original image URLs within an EPUB are rewritten using the default configuration after calling getChapter(). ```html ``` -------------------------------- ### Accessing Manifest Items and Content Source: https://github.com/julien-c/epub/blob/master/_autodocs/types.md Demonstrates iterating through the EPUB's reading order (flow) and accessing individual manifest items by ID to retrieve chapter content. ```typescript const epub = new EPub("book.epub"); await epub.parse(); // Access via flow (reading order) for (const item of epub.flow) { console.log(item.id); // e.g., "ch01" console.log(item.href); // e.g., "OEBPS/ch01.xhtml" console.log(item["media-type"]); // e.g., "application/xhtml+xml" } // Access via manifest (by ID) const item = epub.manifest["ch01"]; const content = await epub.getChapter(item.id); ``` -------------------------------- ### Accessing EPub Manifest Items Source: https://github.com/julien-c/epub/blob/master/_autodocs/api-reference/EPub.md Shows how to access individual resources within the EPUB manifest using their item ID. ```typescript const epub = new EPub("book.epub"); await epub.parse(); // Get resource by ID const item = epub.manifest["chapter1"]; console.log(item.href); console.log(item["media-type"]); ``` -------------------------------- ### EPUB Constructor Normalization Source: https://github.com/julien-c/epub/blob/master/_autodocs/configuration.md Demonstrates how the 'imageroot' and 'linkroot' constructor parameters are automatically normalized by appending a trailing slash if missing. This ensures consistent URL prefixes for images and links. ```typescript const epub = new EPub("book.epub", "images", "chapters"); console.log(epub.imageroot); // "images/" console.log(epub.linkroot); // "chapters/" ``` -------------------------------- ### Accessing EPub Version Source: https://github.com/julien-c/epub/blob/master/_autodocs/api-reference/EPub.md Shows how to retrieve the EPUB specification version (e.g., '2.0' or '3.0') after parsing the file. ```typescript const epub = new EPub("book.epub"); await epub.parse(); console.log(epub.version); ``` -------------------------------- ### EPUB Module Import Patterns Source: https://github.com/julien-c/epub/blob/master/_autodocs/types.md Shows common ways to import the EPub class and its associated types from the 'epub' module, using default or named imports. ```typescript import EPub, { Metadata, ManifestItem, TocElement } from "epub"; // Or with named imports import { EPub, Metadata, ManifestItem, TocElement } from "epub"; ``` -------------------------------- ### Configure URL Prefixes Source: https://github.com/julien-c/epub/blob/master/_autodocs/README.md Customize the prefixes for image and chapter URLs when initializing the EPub class. This affects how URLs are rewritten within the HTML content. ```typescript const epub = new EPub("book.epub", "/images/", "/chapters/"); ``` -------------------------------- ### EPub Constructor with Custom Link Root Source: https://github.com/julien-c/epub/blob/master/_autodocs/configuration.md Configure a custom URL prefix for chapter links. Anchors are preserved in rewritten URLs. ```typescript const epub = new EPub("book.epub", "/images/", "/chapters/"); await epub.parse(); await epub.getChapter("ch01"); // becomes ``` -------------------------------- ### Link URL Rewriting with Default Config Source: https://github.com/julien-c/epub/blob/master/_autodocs/configuration.md Shows how original link URLs within an EPUB are rewritten using the default configuration after calling getChapter(). ```html ``` -------------------------------- ### CDN URLs for EPub Assets Source: https://github.com/julien-c/epub/blob/master/_autodocs/configuration.md Instantiates an EPub object using a CDN URL for images and a relative path for chapters. ```typescript const epub = new EPub("book.epub", "https://cdn.example.com/books/images/", "/chapters/"); ``` -------------------------------- ### EPub Constructor with ArrayBuffer Source: https://github.com/julien-c/epub/blob/master/_autodocs/configuration.md Instantiate EPub using an ArrayBuffer. Suitable for network-based fetching or browser environments. ```typescript const response = await fetch("https://example.com/book.epub"); const arrayBuffer = await response.arrayBuffer(); const epub = new EPub(arrayBuffer); ``` -------------------------------- ### EPub Constructor Signature Source: https://github.com/julien-c/epub/blob/master/_autodocs/README.md The EPub constructor accepts the EPUB file path, an optional image root, and an optional link root. ```typescript new EPub(input: string | Buffer | ArrayBuffer, imageroot?: string, linkroot?: string) ``` -------------------------------- ### walkNavMap(branch, path, idList, level?) Source: https://github.com/julien-c/epub/blob/master/_autodocs/api-reference/EPub.md Recursively walks the navigation map (TOC) of the EPUB and converts it into a flat array of `TocElement` objects, including hierarchy information. ```APIDOC ## walkNavMap(branch, path, idList, level?) ### Description This method is typically called internally by `parse()` but can be used directly for custom processing of the EPUB's Table of Contents (TOC). It traverses the navigation map and structures it into a flat list of TOC elements, preserving their hierarchical relationships. ### Method `walkNavMap(branch: Record | Record[], path: string[], idList: Record, level?: number): TocElement[]` ### Parameters #### Path Parameters - **branch** (`Record | Record[]`) - Required - The navigation point(s) from the TOC XML to process. - **path** (`string[]`) - Required - Base path segments used for resolving relative file references within the TOC. - **idList** (`Record`) - Required - A mapping from file paths to their corresponding manifest IDs. - **level** (`number`) - Optional - The current nesting level in the TOC hierarchy. Defaults to `0`. ### Response #### Success Response - Returns `TocElement[]` - A flat array where each element represents an entry in the TOC, including its level and hierarchy information. ### Example ```typescript const epub = new EPub("book.epub"); await epub.parse(); // Accessing the TOC after parsing (typically populated by parse() itself): console.log(epub.toc); // Filtering TOC entries by level: const topLevelEntries = epub.toc.filter(entry => entry.level === 0); const nestedSections = epub.toc.filter(entry => entry.level === 1); ``` ``` -------------------------------- ### Read EPUB from URL Source: https://github.com/julien-c/epub/blob/master/_autodocs/api-reference/cli.md Shows how to download and read an EPUB file directly from an HTTP or HTTPS URL. ```bash # Download and read from URL epub https://github.com/progit/progit2/releases/download/2.1.449/progit.epub ``` ```bash # Read from HTTP (auto-upgrades to HTTPS) epub http://example.com/book.epub ``` -------------------------------- ### Load Any File from EPUB Source: https://github.com/julien-c/epub/blob/master/README.md Use the getFile method to load any type of file (e.g., CSS, fonts) from the ebook using its ID. The returned data is a Buffer with its MIME type. ```javascript const { data, mimeType } = await epub.getFile("css1"); ``` -------------------------------- ### Parse EPUB and Access Metadata Source: https://github.com/julien-c/epub/blob/master/README.md After initializing the EPub object, call the parse method to load the ebook's contents. You can then access metadata such as the book's title. ```javascript await epub.parse(); console.log(epub.metadata.title); ``` -------------------------------- ### Custom URL Prefixes Source: https://github.com/julien-c/epub/blob/master/_autodocs/getting-started.md Configure custom web paths, CDN URLs, or relative paths for image and chapter links. ```typescript // Custom web paths const epub = new EPub( "./book.epub", "/static/images/", "/static/chapters/" ); // CDN URLs const epub = new EPub( "./book.epub", "https://cdn.example.com/images/", "/api/chapters/" ); // Relative paths const epub = new EPub( "./book.epub", "images/", "chapters/" ); ``` -------------------------------- ### Accessing EPub Metadata Source: https://github.com/julien-c/epub/blob/master/_autodocs/api-reference/EPub.md Shows how to parse an EPUB file and access its metadata properties like title, creator, language, and description. ```typescript const epub = new EPub("book.epub"); await epub.parse(); console.log(epub.metadata.title); console.log(epub.metadata.creator); console.log(epub.metadata.language); console.log(epub.metadata.description); ``` -------------------------------- ### Accessing EPub Spine Structure Source: https://github.com/julien-c/epub/blob/master/_autodocs/api-reference/EPub.md Demonstrates how to access the EPUB spine, which includes the TOC reference and the ordered list of content files. ```typescript const epub = new EPub("book.epub"); await epub.parse(); console.log(epub.spine.toc); console.log(epub.spine.contents); ``` -------------------------------- ### Catch No rootfiles found Error Source: https://github.com/julien-c/epub/blob/master/_autodocs/errors.md Demonstrates catching the 'No rootfiles found' error, which occurs if 'META-INF/container.xml' lacks a '' element or '' children. This error is thrown by EPub.parse() when processing the container file. ```typescript try { await epub.parse(); } catch (err) { if (err instanceof Error && err.message === "No rootfiles found") { console.error("Invalid container.xml: no rootfiles element"); } } ``` -------------------------------- ### Read All Chapters Source: https://github.com/julien-c/epub/blob/master/_autodocs/README.md Loop through the book's flow to retrieve and process the content of each chapter. ```typescript for (const chapter of epub.flow) { const html = await epub.getChapter(chapter.id); // Process chapter content } ``` -------------------------------- ### Read EPUB from URL using CLI Source: https://github.com/julien-c/epub/blob/master/README.md Use the npx or pnpx command to read an EPUB file directly from a URL in your terminal. Ensure the EPUB file is UTF-8 encoded. ```bash URL="https://github.com/progit/progit2/releases/download/2.1.449/progit.epub" npx epub "$URL" # or pnpx epub "$URL" ``` -------------------------------- ### Read Book Metadata Source: https://github.com/julien-c/epub/blob/master/_autodocs/README.md Instantiate the EPub class and parse the book to access its metadata, such as title and creator. ```typescript const epub = new EPub("book.epub"); await epub.parse(); console.log(epub.metadata.title, epub.metadata.creator); ``` -------------------------------- ### API Endpoint Paths for EPub Source: https://github.com/julien-c/epub/blob/master/_autodocs/configuration.md Instantiates an EPub object with API endpoint paths for serving images and chapters in web applications. ```typescript const epub = new EPub("book.epub", "/api/books/images/", "/api/books/chapters/"); ``` -------------------------------- ### Standard EPUB File Structure Source: https://github.com/julien-c/epub/blob/master/_autodocs/architecture.md Outlines the typical directory and file organization within an EPUB archive, including essential files like mimetype, container.xml, package.opf, and content files. ```text book.epub ├── mimetype # "application/epub+zip" ├── META-INF/ │ └── container.xml # Manifest of package documents ├── OEBPS/ # Package directory (varies per EPUB) │ ├── package.opf # Package file with metadata, manifest, spine │ ├── toc.ncx # Table of contents (EPUB 2.0) │ ├── nav.xhtml # Navigation document (EPUB 3.0) │ ├── ch01.xhtml, ch02.xhtml # Content files │ ├── images/ │ │ ├── cover.jpg │ │ └── figure1.png │ └── styles/ │ └── style.css └── [other files] ```