0

I have installed Buffer module via npm install Buffer on my machine and I want to simply import it to the renderer process to use the Buffer

When I use this:

const Buffer = require('Buffer')

it says require is undefined.

None of the solutions on Stack Overflow are working.

halfer
  • 19,824
  • 17
  • 99
  • 186
Sara Ree
  • 3,417
  • 12
  • 48
  • use import instead, check it out this https://stackoverflow.com/questions/31931614/require-is-not-defined-node-js – pbachman Apr 27 '21 at 06:44
  • You may just need to set `nodeIntetration: true`. See [This explanation](https://jameshfisher.com/2020/10/15/how-does-require-work-in-electron/) and/or [this Stack Oveflow question](https://stackoverflow.com/questions/44391448/electron-require-is-not-defined) – Cat Apr 27 '21 at 07:02

2 Answers2

1

Make sure you have nodeIntegration in your BrowserWindow settings set to true and contextIsolation set to false like so:

new BrowserWindow({
    webPreferences:  {
        nodeIntegration:  true,
        contextIsolation: false
    },
});

By default nodeIntegration is false which stops you from using NPM modules in the renderer-process, turning on nodeIntegration will fix this.

Read more here

NOTE: To access the Node.js API from the Renderer process, you need to set the nodeIntegration preference to true and the contextIsolation preference to false.

Disclaimer, turning on nodeIntegration opens up security holes in your app. See Zac's answer on how to fix them.

Joshua
  • 5,032
  • 2
  • 29
  • 45
  • 1
    This answer opens up [security vulnerabilities](https://stackoverflow.com/a/59888788/1837080) in your app. – reZach May 04 '21 at 03:16
  • @Zac Very true, your explanation of these security vulnerabilities is very comprehensive and I appreciate that. – Joshua May 04 '21 at 04:06
0

As the above answer opens up security vulnerabilities, you should instead use preload scripts. preload scripts is a way of exposing some node.js functions to the renderer process without setting the nodeIntegration to true. look at the documentation about preload scripts on www.electronjs.org.

moken
  • 3,227
  • 8
  • 13
  • 23