epubts is a Typescript library for loading EPUB files in browser.

Motivation

I was using the epub JS library in another project but had to work around some shortcomings: The library is intended for a node environment and has node dependencies. Also, I always had to use an async wrapper for the original event based interface. Some more adaptions then justified a complete rewrite in Typescript.

The main benefits of this library over the original include:

  • Async interface
  • Browser friendly dependencies
  • Fully written in Typescript
  • More tests

Compatibility

This library targets EPUB 3.

Installation

epubts is available on npm. You can add it to your project as usual:

# using yarn
yarn add epubts
# using npm
npm install epubts

It uses JSZip to read epub files, so there is no dependency on node. But of course you can use the library in a node environment.

Usage

epubts is written for the browser but can be used in a node environment, for instance your tests.

Using epubts in Browser

This is how you would use epubts to load an epub file in a browser. We assume that the epubFile is already present, for instance through drag & drop.

// Load Epub singleton
import Epub from "epubts";
// Load your file
const epub = await Epub.load(epubFile);
// Get the items ids of the content
const spineItemIds = epub.spine.contents.map(item => item.id);
// Load chapter data
const chapterData = await epub.getChapter(spineItemIds[0]);

Getting a File Object in Node or a Test Environment

If you want to use epubts in nodejs or use it in tests for your browser app, you might need file objects to feed into the API. This is how to get one:

import Epub from "epubts";
import {readFileSync} from 'fs';
...

const epubFileData = readFileSync('./book.epub');
epubFile = new File([epubFileData.buffer], 'book.epub');
const epub = await Epub.load(epubFile);

Remember that File is a dom data structure. For use in node you have to include the dom library in your tsconfig.json.

If you only want to use the library in tests, use vitest like this:

vitest run --environment jsdom

Error Handling

epubts throws pure JS Errors when it ecounters problems. You can handle these in a standard way:

import Epub from "epubts";

try {
const epub = await Epub.load(epubFile);
} catch (e) {
console.log('Error while loading epub: {}', e.message);
}

How to Contribute

If you want to contribute check out epubts on GitHub where you can post pull requests, raise issues and feature requests.