Johannes Stricker
Johannes Stricker

Reputation: 1781

electron: NodeJS 'net' module returns empty object

I just started to work on my first electron app and imported some existing code that uses the net module. When I import the code from the electron app, the net module returns an empty object.

const net = require('net'); // => {}

I thought that electron bundles node together with the required native modules, so I'm a bit confused about why the import isn't working.

EDIT: I've bootstrapped the app with vue-cli-tools, so it's using webpack to bundle dependencies. Not sure if this is important.

Upvotes: 2

Views: 1211

Answers (2)

Quentin
Quentin

Reputation: 943537

I thought that electron bundles node together with the required native modules,

It does, but having a browser runtime and a node.js runtime bundled together still leaves you with two different runtimes.

Understanding the difference between the Main and Renderer processes is essential for Electron development.

The Main process runs on the Node.js runtime and has access to Node.js APIs (like net).

The Renderer process runs on Chromium and has access to browser APIs (like the DOM).

You can't access net from your client-side Vue code because it is running in the Renderer process.

You need to create a service in the Main process and exchange data between it and something running in the Renderer.

This is typically done using the IPC apis.

// In main process.
const { ipcMain } = require('electron')
ipcMain.on('message-from-browser', (event, arg) => {
  const something = doSomethingWithNetModule()
  event.reply('reply-to-browser', something)
})

and

// In renderer process (web page).
const { ipcRenderer } = require('electron')

ipcRenderer.on('asynchronous-reply', (event, arg) => {
    doSomethingWithDataFromNetModule(arg)
})

ipcRenderer.send('message-from-browser', 'do something with the net module please')

Note that since you are using Webpack you will have issues with require("electron") which are explained in this question.

Upvotes: 3

Euan Smith
Euan Smith

Reputation: 2192

Weback may be trying to bundle net. Two things to try:

In vue.config.js configure the externals option with webpack. (note you may neet commonjs2 in the option below, see the externals documentation for more info)

module.exports = {
  configureWebpack: {
    externals: {
      net: 'commonjs net',
    }
  },
}

Alternatively (and less recommended, but has worked in the past when finding the right webpack settings has proved stubborn), rename require so that webpack ignores it:

const _require = require;
//...
const net = _require('net');

Upvotes: 1

Related Questions