'Electron-preload for node methods

I am working on converting my Electron project to use Electron v16 which uses contextBridge for the Node built-in modules.

I currently have this, which uses the net module:

import { Socket } from 'net'

async function portConnection (portConfig) {
  const client = await new Socket()
  client.setKeepAlive(true, 60000)

  return new Promise((resolve, reject) => {
    client.connect(portConfig.port, portConfig.host)

    client.on('connect', () => {
      return resolve(client)
    })

    client.on('timeout', () => {
      return reject(new Error('Connection timeout'))
    })

    client.on('error', (error) => {
      return reject(error)
    })
  })
}

This gives me an error:

TypeError: client.setKeepAlive is not a function

So I added this to the webpack config:

// I know this is not advised, but for simplicity I tried to overwrite the
// 'net' module with one that I preloaded from electron-preload

Object.assign(cfg.externals, {
   net: 'window.netPreload'
})

Then I also moved the setKeepAlive function to electron-preload.js:

import { Socket } from 'net'

let client = null

contextBridge.exposeInMainWorld('netPreload', require('net'))
contextBridge.exposeInMainWorld('netApi', {
  async createClient () {
    client = await new Socket()
    return client
  },
  async keepAlive () {
    if (!client) console.error('No client defined')
    client.setKeepAlive(true, 60000)
  },
  async connect (port, host) {
    if (!client) console.error('No client defined')
    client.connect(port, host)
  }
})

Then I call it like this:

async function portConnection (portConfig) {
  const client = await window.netApi.createClient()
  await window.netApi.setKeepAlive()

  return new Promise((resolve, reject) => {
    client.connect(portConfig.port, portConfig.host)

    client.on('connect', () => {
      return resolve(client)
    })

    client.on('timeout', () => {
      return reject(new Error('Connection timeout'))
    })

    client.on('error', (error) => {
      return reject(error)
    })
  })
}

Now I am getting an error:

TypeError: client.on is not a function

I dont really want to add a contextBridge method for each method in 'net' module. Is there any way to do this?

Also, in this case, how can I 'overwrite' with a polyfill the <net.Server> returned by the command new Socket()?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source