Julian
Julian

Reputation: 21

How to Require N-api from electron

I am currently trying to build a native C++ add-on for an electron app.

I have successfully built and ran a testaddon.node from the index.js file as specified in the following link (really is a fantastic guide, very worth a read).

https://medium.com/@atulanand94/beginners-guide-to-writing-nodejs-addons-using-c-and-n-api-node-addon-api-9b3b718a9a7f

I am currently including the addon I made in my package.json folder, and running my electron app via npm start.

However, I cannot seem to get at the require('./test-addon/build/Release/testaddon.node');

My best guess is that the folder is simply not making it into my .asar. I have tried every conceivable combination of electron-rebuilder, electron packager, etc.

From what I see, electron.asar only triggers when I modify the node_modules folder through node. However, I don't see how to do this if I am making my own C++ module.

Upvotes: 2

Views: 2022

Answers (2)

Дід Alik
Дід Alik

Reputation: 319

Try the bindings module,

https://github.com/TooTallNate/node-bindings

, it finds and loads your native .node file. Works for me as follows:

const B2 = require('bindings')('b2')

This line has been taken from here

Upvotes: 1

Julian
Julian

Reputation: 21

After considerable smashing my head into a wall, I used these tutorials. Please note that some of the C++ code is now out of date, particularly with the later examples. However, the first 3 or 4 examples build and run fine.

https://github.com/nodejs/abi-stable-node-addon-examples

1) Make sure your example works as advertised in the node addon example link. 2) Bring it into your electron build. 3) Make sure that you run .\node_modules.bin\electron-rebuild.cmd after install

The require will be the same from the electron renderer as it is from the example file.

Upvotes: 0

Related Questions