0

I am trying to build an electron Desctop app but when I wanted to use the Filesystem (fs) of nodejs I got the error "Uncaught ReferenceError: require is not defined". When I searched for the problem I found some tipps like "delete "type:" "module" " from your package.json or to use import instead but nothing worked out for me. I can not use any modules in general not just fs but everything in my main.js works just fine.

const { app, BrowserWindow } = require('electron');
const path = require('path');

// Handle creating/removing shortcuts on Windows when installing/uninstalling.
if (require('electron-squirrel-startup')) { // eslint-disable-line global-require
  app.quit();
}

const createWindow = () => {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true
    }
  });

As you can see require() works but only there. It does not work when I want to use it in my index.html to read a file.

const { readFile } = require('fs');
readFile('./foo.txt', (err, source) => {
  if (err) {
    console.error(err);
  } else {
    console.log(source);
  }
});
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Test</title>
    <link rel="stylesheet" href="index.css" />
    <script defer src="test.js"></script>
  </head>
  <body class="content">
  </body>
</html>

I am not really an experienced programmer so I hope I don't make an obvious mistake and waste your time and I am looking forward to your help.

alexmac
  • 19,087
  • 7
  • 58
  • 69
Blue
  • 1
  • You can rewrite `const { readFile } = require('fs')` into `import { readFile } from "fs"` – Jeremy Thille Aug 20 '21 at 13:12
  • I did already try that I had to add the "type= module" to my script tag but it still didn't work it just gave me another error: "Uncaught TypeError: Failed to resolve module specifier "fs". Relative references must start with either "/", "./", or "../". " – Blue Aug 20 '21 at 13:17

1 Answers1

0
function createAddItemWindow() {

    // Create a new window
    addItemWindown = new BrowserWindow({
        width: 300,
        height: 200,
        title: 'Add Item',

        // The lines below solved the issue
        webPreferences: {
            nodeIntegration: true
        }
})}

The solution was proposed here.

Moaud louhichi
  • 623
  • 5
  • 9