Native addon
- Node.js course
- Expert
- Lesson 44/47
- 6 min
Write a native addon with N-API.
The native addon layer
In the second lesson we add the native addon layer. N-API is Node.js's stable interface for calling C/C++ libraries from JavaScript. In this project, instead of compiling a real N-API module, we write a nativeAddon function that stands in for it.
The nativeAddon function returns { api: 'N-API', status: 'hazır' }. This carries which interface the native layer plugs in with and its readiness. Output: N-API: hazır. The previous lesson's setupProject solution sits at the top of the starting code, so the application grows cumulatively. A real N-API module is compiled with node-gyp and loaded with require; here we model it.
Cumulative growth
In each lesson of the project the starting code contains the previous lesson's solution. This cumulative growth guarantees that, by the final lesson, all layers work together. In this lesson, nativeAddon is added on top of setupProject.
The output carries the previous lesson's ExpertProject and 1.0 lines, then a new line shows N-API: hazır. This way the output of two lessons accumulates. The nativeAddon call has the form console.log(nativeAddon().api + ': ' + nativeAddon().status). This pattern repeats later for distributedLayer and performanceLayer. Cumulative growth makes the final integration lesson natural.
Practice Add the native addon layer
Take the previous lesson's setupProject solution. Add function nativeAddon(); return { api: 'N-API', status: 'hazır' }. Print console.log(nativeAddon().api + ': ' + nativeAddon().status).
Starter code
function setupProject() {
return { name: 'ExpertProject', version: '1.0' };
}
console.log(setupProject().name);
console.log(setupProject().version);
// Write the nativeAddon function
// Return an object holding the N-API flag
// Print api and status as 'api: status'
// write hereSample solution
function setupProject() {
return { name: 'ExpertProject', version: '1.0' };
}
console.log(setupProject().name);
console.log(setupProject().version);
function nativeAddon() {
return { api: 'N-API', status: 'hazır' };
}
console.log(nativeAddon().api + ': ' + nativeAddon().status);Expected output
ExpertProject 1.0 N-API: hazır
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the api field
return { api: '____', status: 'hazır' };
return { api: 'N-API', status: 'hazır' };
Explanation: The api field carries 'N-API'.
2 Match each piece to its role
| Term | Meaning |
|---|---|
N-API |
Native interface |
nativeAddon |
Layer function |
api |
Interface name |
status |
Readiness |
3 What does N-API provide?
function nativeAddon() { return {api: 'N-API', status: 'hazır'}; }- Calling a native library from JavaScript Correct answer
- An HTTP request
- Dosya okuma
- Joining tables
Explanation: N-API lets JavaScript call C/C++ libraries.