futurepress / epub.js

Enhanced eBooks in the browser.
http://futurepress.org
Other
6.3k stars 1.08k forks source link

`ReferenceError: window is not defined` when creating Book object from path in Node.js due to url.js #1168

Open wyatttroutman opened 3 years ago

wyatttroutman commented 3 years ago

Hello, I am attempting to use the epubjs npm package in Node.js (current LTS version, V14) to read metadata from an epub file.

In my Node.js code, I am importing the Book class:

import { Book } from "epubjs";

then, I attempt to create a Book object from a filepath, path:

const book = new Book(path);

In this scenario, the path is a local filepath being sent to an Express Web API, where I am trying to load the file to gather metadata and return it in the API response. For additional context, I am running the Express instance from an Electron app built via electron-webpack. The Electron app is what is communicating to the local Express instance.

However, I am getting this error on that line:

  ReferenceError: window is not defined
      at new Url (webpack-internal:///./node_modules/epubjs/src/utils/url.js:32:5)
      at Book.determineType (webpack-internal:///./node_modules/epubjs/src/book.js:443:9)
      at Book.open (webpack-internal:///./node_modules/epubjs/src/book.js:269:27)
      at new Book (webpack-internal:///./node_modules/epubjs/src/book.js:253:9)
      at eval (webpack-internal:///./public/express/app.js:46:25)

My guess is that in url.js, this code is causing a problem:

if (!absolute &&
    baseString !== false &&
    typeof(baseString) !== "string" &&
    window && window.location) {
   this.base = window.location.href;
}

But I am not sure how to resolve it. Any help is appreciated.

sbatson5 commented 3 years ago

It sounds like you are running the app in a Node environment and not in a browser environment (which is where window is defined). Epub.js won't work in Node/Express as it's a UI library that requires a browser.

Sec-ant commented 2 years ago

I'm facing the same problem. Creating a Book instance and reading metadata from a file shouldn't have anything to do with UI. Is there a way to use these functionalities in Node? Or any other node alternatives to parse metadata from a .epub file?