### Run Example Script Source: https://github.com/dylanarmstrong/nodepub/blob/main/README.md Executes an example script to generate a final Epub. This command is run from the top folder containing the 'package.json' file. ```bash pnpm run example ``` -------------------------------- ### Install Nodepub Source: https://github.com/dylanarmstrong/nodepub/blob/main/README.md Install the Nodepub package using npm or pnpm. ```sh npm install @dylanarmstrong/nodepub # or pnpm add @dylanarmstrong/nodepub ``` -------------------------------- ### Import Nodepub Source: https://github.com/dylanarmstrong/nodepub/blob/main/README.md Import the Epub class from the Nodepub module after installation. ```javascript import Epub from '@dylanarmstrong/nodepub'; ``` -------------------------------- ### Create an Ebook with Nodepub Source: https://context7.com/dylanarmstrong/nodepub/llms.txt Demonstrates the full workflow including metadata configuration, section definition, resource loading, and writing the final EPUB file. ```typescript import Epub from '@dylanarmstrong/nodepub'; import { readFile } from 'node:fs/promises'; async function createEbook() { // Load cover and resources const coverData = await readFile('./assets/cover.png'); const hatImage = await readFile('./assets/hat.png'); const css = ` body { font-family: Verdana, Arial, sans-serif; font-size: 11pt; } #title, #title h1, #title h2 { text-align: center; } h1, h3, p { margin-bottom: 1em; } p { text-indent: 0; } p + p { text-indent: 0.75em; } img { max-width: 100%; height: auto; } `; const metadata = { author: 'Anonymous', contents: 'Chapters', copyright: 'Anonymous, 2024', cover: { data: coverData, name: 'cover.png' }, description: 'A complete example ebook.', fileAs: 'Anonymous', genre: 'Non-Fiction', id: '978-0-123456-78-9', language: 'en', published: '2024-01-01', publisher: 'Example Press', sequence: 1, series: 'Example Series', source: 'https://example.com', tags: ['Example', 'Tutorial', 'Sample'], title: 'Complete Example Book', }; const sections = [ { title: 'Title Page', content: `

Complete Example Book

Book 1 of Example Series

Anonymous

© Anonymous, 2024

`, isFrontMatter: true, excludeFromContents: true, }, { title: 'Copyright', content: `

Copyright Notice

All rights reserved. No part of this book may be reproduced.

This book is a work of fiction.

`, filename: 'copyright-page', isFrontMatter: true, }, { title: 'Chapter 1', content: `

Chapter One

This is the first chapter of our example book.

Continue to Chapter 2.

`, }, { title: 'Chapter 2', content: `

Chapter Two

This chapter includes an image:

A hat

`, }, { title: 'About the Author', content: `

About the Author

Anonymous writes example books for documentation purposes.

`, }, ]; const resources = [ { data: hatImage, name: 'assets/hat.png' }, ]; const options = { coverType: 'image' as const, showContents: true, }; const epub = new Epub({ css, metadata, options, resources, sections, }); try { await epub.write('./output', 'complete-example.epub'); console.log('EPUB created: ./output/complete-example.epub'); } catch (error) { console.error('Failed to create EPUB:', error); process.exit(1); } } createEbook(); ``` -------------------------------- ### Create Epub with Metadata, Sections, and Resources Source: https://github.com/dylanarmstrong/nodepub/blob/main/README.md Instantiate the Epub class with metadata, sections, optional CSS, options, and resources. Ensure resources like cover images are read into memory. ```javascript const metadata = { author: 'Dylan', contents: 'Chapters', copyright: 'Dylan, 2023', cover: 'example/cover.png', description: 'A test book.', fileAs: 'Dylan', genre: 'Non-Fiction', id: '1234', language: 'en', published: '1992-06-17', publisher: 'My Fake Publisher', sequence: 1, series: 'My Series', source: 'https://dylan.is', tags: ['Sample', 'Example', 'Test'], title: 'My First Book', }; const resources = [{ data: await readFile('../example/hat.png'), name: '../example/hat.png', }]; const sections = [ { content: 'This is a libre book with no copyright', excludeFromContents: true, filename: 'copyright-page', isFrontMatter: true, title: 'Copyright', }, { content: 'Chapter 1', title: '

Chapter One

...

', }, { content: 'Chapter 2', title: '

Chapter Two

...

', }, ]; const css = ` table { border: 3px double #ccc; margin-left: auto; margin-right: auto; padding: 0.5em; } `; const options = { showContents: true, coverType: 'image', // Possible types are 'image' and 'text' }; const epub = new Epub({ metadata, sections, // Optional css, options, resources, }); ``` -------------------------------- ### Initialize Epub Instance Source: https://context7.com/dylanarmstrong/nodepub/llms.txt Configure the Epub class with metadata, sections, resources, CSS, and rendering options. ```typescript import Epub from '@dylanarmstrong/nodepub'; import { readFile } from 'node:fs/promises'; // Define book metadata (required fields: author, cover, id, title) const metadata = { author: 'Jane Doe', title: 'My Adventure Novel', id: 'isbn:978-3-16-148410-0', cover: { data: await readFile('./images/cover.png'), name: 'cover.png', }, // Optional metadata fields contents: 'Table of Contents', // TOC title copyright: 'Jane Doe, 2024', description: 'An exciting adventure story.', fileAs: 'Doe, Jane', // Sortable author name genre: 'Fiction', // Primary subject language: 'en', // ISO language code published: '2024-01-15', // YYYY-MM-DD format publisher: 'Self Published', series: 'Adventure Series', sequence: 1, // Position in series (for Calibre), source: 'https://example.com', tags: ['Adventure', 'Fiction'], // Additional subjects }; // Define book sections/chapters const sections = [ { title: 'Title Page', content: '

My Adventure Novel

by Jane Doe

', isFrontMatter: true, // Place before TOC excludeFromContents: true, // Hide from TOC }, { title: 'Chapter 1', content: '

Chapter 1: The Beginning

It all started on a rainy day...

', }, { title: 'Chapter 2', content: '

Chapter 2: The Journey

The path led through the forest...

', filename: 'chapter-2', // Custom filename (becomes chapter-2.xhtml) }, ]; // Define inline resources (images, audio) const resources = [ { data: await readFile('./images/map.png'), name: 'images/map.png', }, { data: await readFile('./audio/chapter1.mp3'), name: 'audio/chapter1.mp3', }, ]; // Custom CSS (appended to default styles) const css = ` body { font-family: Georgia, serif; font-size: 12pt; } h1 { text-align: center; margin-bottom: 2em; } p { text-indent: 1em; margin-bottom: 0.5em; } `; // Rendering options const options = { showContents: true, // Include TOC page (default: true) coverType: 'image', // 'image' or 'text' (default: 'image') }; // Create the Epub instance const epub = new Epub({ metadata, sections, resources, // Optional css, // Optional options, // Optional }); ``` -------------------------------- ### Epub Class Constructor Source: https://context7.com/dylanarmstrong/nodepub/llms.txt Initializes a new Epub instance with book metadata, content sections, resources, and styling options. ```APIDOC ## Constructor: new Epub(config) ### Description Creates an instance of the Epub class. The configuration object defines the structure and content of the ebook. ### Parameters #### Request Body - **metadata** (object) - Required - Contains book details: author, title, id, cover, and optional fields like language, genre, and series. - **sections** (array) - Required - An array of objects representing chapters, each containing title, content, and optional flags like isFrontMatter. - **resources** (array) - Optional - Array of objects containing data and name for images or audio files. - **css** (string) - Optional - Custom CSS string to style the ebook content. - **options** (object) - Optional - Rendering settings such as showContents and coverType. ### Request Example { "metadata": { "author": "Jane Doe", "title": "My Adventure Novel", "id": "isbn:978-3-16-148410-0", "cover": { "data": "", "name": "cover.png" } }, "sections": [ { "title": "Chapter 1", "content": "

Chapter 1

" } ] } ``` -------------------------------- ### Generate EPUB File with write() Source: https://context7.com/dylanarmstrong/nodepub/llms.txt Use the write method to bundle resources and compress the EPUB into a zip archive. The method automatically appends the .epub extension if missing and creates the target directory if it does not exist. ```typescript import Epub from '@dylanarmstrong/nodepub'; import { readFile } from 'node:fs/promises'; const metadata = { author: 'John Smith', title: 'Quick Guide', id: '12345', cover: { data: await readFile('./cover.jpg'), name: 'cover.jpg', }, }; const sections = [ { title: 'Introduction', content: '

Introduction

Welcome to this guide.

', }, ]; const epub = new Epub({ metadata, sections }); // Write EPUB to specified folder with filename // Creates 'output/my-book.epub' try { await epub.write('output', 'my-book.epub'); console.log('EPUB created successfully!'); } catch (error) { console.error('Failed to create EPUB:', error); } // Extension is added automatically if omitted // Creates 'output/my-book.epub' await epub.write('output', 'my-book'); // Folder is created if it doesn't exist await epub.write('./books/2024', 'new-release'); ``` -------------------------------- ### Embed Multimedia Resources in EPUB Source: https://context7.com/dylanarmstrong/nodepub/llms.txt Load local files as buffers and reference them in HTML content using the relative path ../resources/. Duplicate resource names are automatically handled. ```typescript import Epub from '@dylanarmstrong/nodepub'; import { readFile } from 'node:fs/promises'; const metadata = { author: 'Media Author', title: 'Multimedia Book', id: 'multimedia-001', cover: { data: await readFile('./images/cover.png'), name: 'cover.png' }, }; // Load resources as buffers const resources = [ { data: await readFile('./images/diagram.png'), name: 'images/diagram.png', }, { data: await readFile('./images/photo.jpg'), name: 'photos/author.jpg', }, { data: await readFile('./audio/narration.mp3'), name: 'audio/chapter1-narration.mp3', }, ]; const sections = [ { title: 'Chapter with Images', content: `

Visual Guide

Here is an important diagram:

System diagram

And a photo:

Author

`, }, { title: 'Chapter with Audio', content: `

Listen Along

Audio narration for this chapter:

`, }, ]; const epub = new Epub({ metadata, sections, resources }); await epub.write('./output', 'multimedia-book'); // Note: Duplicate resources (same name) are automatically removed const duplicateResources = [ { data: await readFile('./img/logo.png'), name: 'logo.png' }, { data: await readFile('./img/logo.png'), name: 'logo.png' }, // Ignored ]; ``` -------------------------------- ### Configure Advanced Epub Options Source: https://github.com/dylanarmstrong/nodepub/blob/main/README.md Sets advanced options for Epub generation, such as including a Table of Contents (TOC) or specifying the cover type. These options are passed via the 'options' parameter. ```javascript const options = { showContents: true, // Whether or not to include the TOC page (default: true) coverType: 'image', // Possible types are 'image' and 'text' (default: 'image') }; const epub = createEpub({ metadata, options, sections, }); ``` -------------------------------- ### write() Method Source: https://context7.com/dylanarmstrong/nodepub/llms.txt Generates the final EPUB file and saves it to the specified directory. ```APIDOC ## Method: write(outputDir, filename) ### Description Processes the internal data structure, bundles resources, and writes the final .epub file to the disk. ### Parameters #### Path Parameters - **outputDir** (string) - Required - The directory path where the file will be saved. - **filename** (string) - Required - The name of the file. If the .epub extension is omitted, it is added automatically. ### Response #### Success Response (200) - **void** - Returns a promise that resolves when the file is successfully written. ### Request Example await epub.write('output', 'my-book.epub'); ``` -------------------------------- ### Include Resources in Epub Source: https://github.com/dylanarmstrong/nodepub/blob/main/README.md Defines resources like images or mp3s to be included in the Epub. Ensure filenames are unique as they are placed in a common internal 'resources' folder. ```javascript const resources = [{ data: await readFile('../example/hat.png'), name: '../example/hat.png', }]; ``` -------------------------------- ### Inspect EPUB Files with getFiles() Source: https://context7.com/dylanarmstrong/nodepub/llms.txt Use the getFiles() method to retrieve an array of all files that will be included in the EPUB archive. This allows for inspection or custom post-processing before writing the EPUB. Each file object includes compression settings, content, folder path, and filename. ```typescript import Epub from '@dylanarmstrong/nodepub'; const metadata = { author: 'Test Author', title: 'Test Book', id: 'test-123', cover: { data: Buffer.from([0x89, 0x50, 0x4E, 0x47]), // PNG header bytes name: 'cover.png', }, }; const sections = [ { title: 'Chapter 1', content: '

Chapter 1

Content here.

' }, { title: 'Chapter 2', content: '

Chapter 2

More content.

' }, ]; const epub = new Epub({ metadata, sections }); const files = epub.getFiles(); // Inspect the generated file structure files.forEach((file) => { console.log(`${file.folder}/${file.name} (compress: ${file.compress})`); }); // Output: // /mimetype (compress: false) // META-INF/container.xml (compress: true) // OPS/ebook.opf (compress: true) // OPS/cover.xhtml (compress: true) // OPS/css/ebook.css (compress: true) // OPS/content/s1.xhtml (compress: true) // OPS/content/s2.xhtml (compress: true) // OPS/content/toc.xhtml (compress: true) // OPS/resources/cover.png (compress: true) // Access specific file content const opfFile = files.find((f) => f.name === 'ebook.opf'); console.log(opfFile?.content); // XML content of the OPF manifest ``` -------------------------------- ### Write Epub to File Source: https://github.com/dylanarmstrong/nodepub/blob/main/README.md Generates and writes the final Epub file to the specified directory and filename. This is an asynchronous operation. ```javascript await epub.write(folder, filename); ``` -------------------------------- ### Configure Text-Based Cover Source: https://context7.com/dylanarmstrong/nodepub/llms.txt Use an HTML string for the cover by setting coverType to 'text' in the options object. ```typescript import Epub from '@dylanarmstrong/nodepub'; const metadata = { author: 'Classic Author', title: 'Public Domain Work', id: 'pd-12345', // Cover as HTML string instead of image buffer cover: `

Public Domain Work

A Classic Novel

by Classic Author

Originally published 1890

`, }; const sections = [ { title: 'Preface', content: '

Preface

Introduction to this classic work...

', }, ]; const options = { coverType: 'text' as const, // Use HTML cover instead of image showContents: true, }; const epub = new Epub({ metadata, sections, options }); await epub.write('./output', 'classic-work'); ``` -------------------------------- ### Modify Epub Styling with CSS Source: https://github.com/dylanarmstrong/nodepub/blob/main/README.md Injects basic CSS to override default styling. Use sparingly due to inconsistent support across ereaders. Modify the 'css' parameter of 'createEpub'. ```javascript const css = `p { text-indent: 0; } p+p { text-indent: 0.75em; }`); const epub = new Epub({ css, resources, metadata, sections, }); ``` -------------------------------- ### Configure EPUB Sections Source: https://context7.com/dylanarmstrong/nodepub/llms.txt Define sections for chapters or content divisions in an EPUB. Each section requires a title and HTML content. Optional properties like `isFrontMatter`, `excludeFromContents`, and `filename` control TOC visibility, placement, and internal linking. ```typescript import Epub from '@dylanarmstrong/nodepub'; import { readFile } from 'node:fs/promises'; const metadata = { author: 'Author Name', title: 'Complete Book', id: 'complete-book-001', cover: { data: await readFile('./cover.png'), name: 'cover.png' }, }; const sections = [ // Front matter: appears before TOC, hidden from TOC { title: 'Title Page', content: `

Complete Book

A Novel

by Author Name

`, isFrontMatter: true, excludeFromContents: true, }, // Copyright page: front matter but shown in TOC { title: 'Copyright', content: '

Copyright Notice

© 2024 Author Name. All rights reserved.

', isFrontMatter: true, filename: 'copyright-page', // Allows internal linking }, // Regular chapters (appear after TOC) { title: 'Chapter 1: The Beginning', content: `

Chapter 1

The story begins here.

For more, see Chapter 2.

`, filename: 'chapter-1', }, { title: 'Chapter 2: The Middle', content: `

Chapter 2

The story continues.

Return to Chapter 1.

`, filename: 'chapter-2', }, // Hidden section: not in TOC but still in the book { title: 'Secret Bonus Chapter', content: '

Bonus!

You found the secret chapter.

', excludeFromContents: true, }, // Back matter { title: 'About the Author', content: `

About the Author

Author biography here.

Author photo

`, }, ]; const epub = new Epub({ metadata, sections }); await epub.write('./output', 'complete-book'); ``` -------------------------------- ### Suppress Table of Contents Source: https://context7.com/dylanarmstrong/nodepub/llms.txt Disable the generated TOC page by setting showContents to false in the options. ```typescript import Epub from '@dylanarmstrong/nodepub'; import { readFile } from 'node:fs/promises'; const metadata = { author: 'Short Story Author', title: 'A Single Story', id: 'short-001', cover: { data: await readFile('./cover.png'), name: 'cover.png' }, }; // For a single-chapter work, TOC is unnecessary const sections = [ { title: 'The Story', content: `

A Single Story

This is a complete short story in one chapter.

No table of contents needed.

`, }, ]; const options = { showContents: false, // No TOC page generated }; const epub = new Epub({ metadata, sections, options }); await epub.write('./output', 'single-story'); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.