Node.js
Native addon
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.
Exercise 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).
Show example 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);
Test yourself
-
Complete the api field
return { api: '____', status: 'hazır' };
Show answer
return { api: 'N-API', status: 'hazır' };
-
Match each piece to its role
- N-API
- Native interface
- nativeAddon
- Layer function
- api
- Interface name
- status
- Readiness
-
What does N-API provide?
function nativeAddon() { return {api: 'N-API', status: 'hazır'}; }
- Calling a native library from JavaScript
- An HTTP request
- Dosya okuma
- Joining tables
Show answer
Calling a native library from JavaScript — N-API lets JavaScript call C/C++ libraries.
Next lesson: Distributed