Lab 05: Native Addons

Time: 60 minutes | Level: Architect | Docker: docker run -it --rm node:20-alpine sh

Native addons let Node.js call C/C++ code directly, unlocking SIMD, hardware I/O, legacy libraries, and extreme performance. This lab covers N-API with node-addon-api, node-gyp compilation, and FFI as an alternative.


Step 1: Why Native Addons?

Use cases:

  • CPU-intensive algorithms (image processing, crypto, compression)

  • System-level APIs (hardware access, OS-specific features)

  • Wrapping existing C/C++ libraries (OpenCV, BLAS, SQLite)

  • Real-time constraints (audio processing, robotics)

N-API (Node-API) provides a stable ABI — addons compiled for Node 16 work on Node 20+ without recompilation.


Step 2: Install Build Tools

# In Docker container:
apk add --no-cache python3 make g++ py3-pip
npm install -g node-gyp

# On Debian/Ubuntu:
# apt install python3 make g++ -y
# npm install -g node-gyp

💡 node-gyp uses Python to drive the GYP build system (Google's build tool). Always have Python 3.x installed.


Step 3: C Source — N-API Hello World


Step 4: binding.gyp Build Configuration

💡 target_name matches the output filename: build/Release/hello.node


Step 5: JavaScript Caller

📸 Verified Output (from a real build environment):

💡 N-API addons compiled with node-gyp build produce build/Release/<name>.node — a shared library loaded via require().


Step 6: Using node-addon-api (C++ Wrapper)

node-addon-api provides a C++ class-based wrapper over N-API:

Install and build:


Step 7: FFI Alternative with ffi-napi

For calling existing C libraries WITHOUT writing C code:

💡 ffi-napi is great for prototyping. For production, use N-API for stability and performance (no marshaling overhead).


Step 8: Capstone — Native Fibonacci Benchmark

Build a native addon for Fibonacci and compare performance:

Complete setup and run:


Summary

Method
Language
Stability
Best For

N-API (C)

C

Stable ABI

Lightweight, system calls

node-addon-api

C++

Stable ABI

Complex addons, OOP patterns

ffi-napi

JS

Runtime

Quick bindings to existing .so/.dll

WebAssembly

C/Rust

Universal

Portable compute, sandboxed

child_process

Any

Process

External executables

Last updated