Electron and serial ports

2019-02-20 02:37发布

问题:

I have tried everything to try to get Electron to work with the PCs serial port. Followed all instructions for the serialport (even tried building native modules) without luck.

Has anyone had any luck getting Electron to work with serial ports? If so please share your wisdom.

回答1:

Here are the commands we run after doing npm install (or after upgrading electron or node-serial).

  • on Mac

    rm -rf node_modules/serialport/build/* 
    node_modules/.bin/electron-rebuild -w serialport -f 
    ls node_modules/serialport/build/Release
    
  • on Win

    rmdir /S /Q node_modules\serialport\build\ 
    node_modules\.bin\electron-rebuild -w serialport -f
    dir node_modules\serialport\build\Release
    

The root issue is that node-serialport is a native module so you have to compile it or use a pre-built version that corresponds to your version of node. But the version of node electron expects will often (almost always) differ from the version of node you have installed globally. When you rebuild node-serialport you need to target the node version that electron expects. Thankfully, electron-rebuild deals with this. Install it and run it as above. It will figure out what version of electron you are using (assuming you aren't hiding it in some unexpected place).

One other issue we tripped over is that you need to manually delete the build artifacts, before running electron-rebuild, otherwise it doesn't generate new artifacts. It is possible that that's been fixed since I last looked at this.

I include a directly listing as a 3rd command just so I see some output that reassures me the files were generated.

Our solution was based on a super long discussion on the subject in a node-serialport issue. You shouldn't need to read it, but if you do start here https://github.com/EmergingTechnologyAdvisors/node-serialport/issues/538#issuecomment-273927595, where they say:

I think this issue should be closed, right? This is not an issue, haven't been for a long time cause node-serialport works just fine with Electron.

The main problem is that of Electron, everyone who starts using Electron will have issues with native modules, and most issues in this thread is about getting native modules to work.

...and then the issue is closed.