N-API
- Node.js course
- Expert
- Lesson 7/47
- 5 min
Learn to write native addons with N-API.
What is N-API?
N-API is the stable application programming interface (API) Node.js offers for writing C/C++ code. N-API provides a contract that does not change across Node.js versions, so a native addon written once runs on many Node.js versions.
Historically addons depended directly on V8 headers; when V8 updated the addon broke. N-API removes this dependency: you write N-API calls and Node.js translates them to V8 internally. A napiModule(name) function models this idea: it returns {name: name, api: 'N-API', version: 9}. N-API version 9 ships with Node.js 22. This abstraction greatly reduces addon maintenance.
The N-API module
An N-API module is a registration function that returns an object to the JS side. napiModule(name) models this: it returns the name, API name and version. In real N-API this is written in C; here we model it in JS.
Example: function napiModule(name) { return {name: name, api: 'N-API', version: 9}; }. napiModule('myaddon') returns {name: 'myaddon', api: 'N-API', version: 9}. console.log(napiModule('myaddon').api + ' v' + napiModule('myaddon').version) prints N-API v9. This is a simple model of N-API module registration; real registration uses the NAPI_MODULE macro but the idea is the same: a name and a set of exports.
Practice Write the N-API module
Write function napiModule(name). Return {name: name, api: 'N-API', version: 9}. Print console.log(napiModule('myaddon').api + ' v' + napiModule('myaddon').version).
Starter code
// Write a napiModule function
// Return {name, api: 'N-API', version: 9}
// Print api and version as 'api vX'
// write hereSample solution
function napiModule(name) {
return {name: name, api: 'N-API', version: 9};
}
console.log(napiModule('myaddon').api + ' v' + napiModule('myaddon').version);Expected output
N-API v9
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does N-API solve?
- Low memory usage
- Addon compatibility across versions Correct answer
- Otomatik testi
- Faster network requests
Explanation: N-API keeps addons compatible across Node.js versions.
2 Return the N-API version
function napiModule(name) { return {name: name, api: 'N-API', version: ____}; }
function napiModule(name) { return {name: name, api: 'N-API', version: 9}; }
Explanation: N-API version 9 ships with Node.js 22.
3 Match each concept to its description
| Term | Meaning |
|---|---|
N-API |
Stable addon interface |
V8 |
JavaScript engine |
addon |
C/C++ extension |
Node.js 22 |
Ships with N-API v9 |