What is wrong with my call to Node's readFile method in an electron renderer?

Viewed 137

I've created a minimal reproduction app which demonstrates my issue based on the "typescript + webpack" template for electron-forge. I have made a few changes in order to demonstrate my issue and you can find the entire app here. The README contains all necessary reproduction instructions (dead simple).

Basically what I've done is create a src/other.html file, and my goal is to load the contents of this file and replace the #main-content div's contents (located in src/index.html) with the new contents. The code to do this is located in src/renderer.ts but here is the code in question:

import fs from "fs";
import path from "path";

const contentElement = document.getElementById("main-content");
const linkElement = document.getElementById("switch");

if (!contentElement) throw "Unable to find main content div.";
if (!linkElement) throw "Unable to find link element.";

linkElement?.addEventListener("click", (event) => {
  event.preventDefault();

  const href = linkElement.getAttribute("href");

  if (href) {
    const fullPath = path.join(__dirname, href);

    console.log(`Full path: ${fullPath}`);

    fs.readFile(fullPath, (err, data) => {
      if (err) throw err;

      // show the selected page
      contentElement.innerHTML = "";
      contentElement.insertAdjacentHTML("beforeend", data.toString());
    });
  }
});

It adds a click handler which grabs the href attribute value and attempts to construct the new file's path with __dirname, given that the two HTML files are in the same directory.

Instead of this code working as expected I encounter the following error in the dev console:

dev console error

Uncaught Error: Invalid package /Users/taylorthurlow/Temp/electron-problem-min-repro/node_modules/electron/dist/Electron.app/Contents/Resources/electron.asar
    at createError (electron/js2c/asar_bundle.js:5)
    at Object.e.readFile (electron/js2c/asar_bundle.js:5)
    at HTMLAnchorElement.<anonymous> (renderer.ts:50)
createError @ electron/js2c/asar_bundle.js:5
e.readFile @ electron/js2c/asar_bundle.js:5
(anonymous) @ renderer.ts:50

The console log call prints:

Full path: /Users/taylorthurlow/Temp/electron-problem-min-repro/node_modules/electron/dist/Electron.app/Contents/Resources/electron.asar/renderer/other.html

I took a look at the Resources directory that electron.asar is expected to be inside of, but I only see default_app.asar and some other unrelated stuff. I assume this is why I'm getting the error. I don't understand enough about javascript/typescript or any of the ecosystem surrounding it to really understand what's going on here.

Some version numbers:

  • electron-forge v6 beta 54
  • electron 11.0.3
  • node 12.20.0
0 Answers
Related