'What to use on Nodejs addons. Node.h or Napi.h
I have some pretty simple questions.
- What is the main difference between node.h and napi.h.
- What should I use for normal/personal use case.
- Why are there more "nodejs" headers. (node.h, napi.h, nan.h, node_api.h, ...)
I have looked on Internet for answers on these questions but I could find any. I'm sorry if this is one of the must know things, but I started with addons recently.
Solution 1:[1]
There are four different interfaces for a Node.js addons
- The raw
node.h
(C++) which is no interface at all - in this case you will have to deal with different V8/Node.js versions - which is very hard and cumbersome; - The old Node.js Nan (C++) which is still maintained and it allows you to have an uniform C++ API across all Node.js versions - but it requires that your addon is built separately for every Node.js version and does not support
worker_threads
; - The new
napi.h
(C) which has an uniform ABI across all versions - meaning that a binary module built for one version will work with all later versions; - The newest Node Addon API (C++) which is a set of C++ classes around
napi.h
that allows you to use NAPI with C++ semantics. It is fully compatible withnapi.h
and you can mix the two.
For a new module, Node Addon API is by far the best choice.
Solution 2:[2]
What is the main difference between node.h and napi.h.
Refering the nodejs doc (https://nodejs.org/dist/latest/docs/api/n-api.html#node-api) : (napi.h) It is independent from the underlying JavaScript runtime (for example, V8) and is maintained as part of Node.js itself.
When you write a node addon using node.h you have to deal with v8 stuff, and your code will be coupled to v8. Using napi.h (or node_api.h the c++ wrapper of napi.h) remove the coupling to v8, so if the node team decide to move to an another javascript backend (they will never do that, but IF they do) then your code still work without any update.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Dee |
Solution 2 | Bolo |