Search code examples
node.jsangularelectroncapacitor

Using node.js modules in electron



I have the following use case:
I want to develop a desktop application, which will run on a Raspberry Pi. I decided to use Electron to build the desktop application and Angular as the frontend framework (1).

I need to use some npm modules for my application in order to communicate with the GPIO-pins or over ethernet tcp communication ('net' node module). I tried to import these in my Angular application (for example import {Socket} from 'net';), but I don't get them working.

I get the following error when trying to construct the net socket like this: let client = new Socket();

Uncaught (in promise): TypeError: undefined is not a constructor (evaluating 'new net.Socket()')

Is this an error in the base architecture, that I can't run code, which depends on the backend, in the angular frontend. Or am I doing something else wrong?

I also found capacitor (2), which allows to call native sdks. I tried to implement my own plugin, but I get the same error as above.

Thanks for your help.

(1) https://angularfirebase.com/lessons/desktop-apps-with-electron-and-angular/
(2) https://capacitor.ionicframework.com/docs/plugins/


Solution

  • It seems like you have a little confusion about Electron, even thou it is not the classical client:server model, ...

    Lets understand Electron first:


    Main and Renderer Processes

    The main process is for handling/creating BrowserWindows(Renderer) And for some communication from one renderer-Window to an other one. (maybe some other special stuff too)

    The renderer is where you really run the most of your app. With node, you have all you need there.

    you then notice you will be needing a channel between the renderer process (web page) and the main process.

    Don't worry, here is where remote comes in handy :

    Use main process modules from the renderer process.
    

    The remote module provides a simple way to do inter-process communication (IPC) between the renderer process (web page) and the main process.

    ...even the other way round...

    Note: For the reverse (access the renderer process from the main process), you can use webContents.executeJavascript.

    So at the end you will be able of using all the magick in both sides.