Working with Native Addons
1. Understanding N-API (Node-API)
| Aspect | Detail |
|---|---|
| ABI stable | Compiled addon works across Node versions |
| C API | Header node_api.h |
| C++ wrapper | node-addon-api |
2. Creating C++ Addons
Example: hello.cc
#include <napi.h>
Napi::String Hello(const Napi::CallbackInfo& info) {
return Napi::String::New(info.Env(), "world");
}
Napi::Object Init(Napi::Env env, Napi::Object exports) {
exports.Set("hello", Napi::Function::New(env, Hello));
return exports;
}
NODE_API_MODULE(addon, Init)
3. Using node-gyp
| File | Purpose |
|---|---|
binding.gyp | Build config (sources, include_dirs) |
node-gyp configure | Generate platform build files |
node-gyp build | Compile |
node-gyp rebuild | Clean + configure + build |
4. Building Native Modules
| Tool | Use |
|---|---|
node-gyp | Default |
cmake-js | CMake-based |
prebuildify + prebuild-install | Ship prebuilt binaries |
5. Loading Native Modules
Example
import { createRequire } from "node:module";
const require = createRequire(import.meta.url);
const addon = require("./build/Release/addon.node");
console.log(addon.hello());
6. Using node-addon-api
| Feature | Detail |
|---|---|
| RAII C++ wrapper | Around N-API |
| Exception support | Napi::Error::New(env, msg).ThrowAsJavaScriptException() |
| Async work | Napi::AsyncWorker |
7. Cross-Platform Compilation
| Concern | Detail |
|---|---|
| Toolchain | MSVC on Windows, clang/gcc on Unix |
| Python | Required by node-gyp |
| CI matrix | Build per (OS × arch × Node ABI) |
8. Debugging Native Code
| Tool | Use |
|---|---|
| gdb / lldb | Attach to node process |
| Visual Studio | Windows native debugging |
--abort-on-uncaught-exception | Core dump on crash |
9. Performance Considerations
| Tip | Detail |
|---|---|
| Cross JS↔C++ boundary cost | Batch calls; avoid hot-loop crossings |
| Use AsyncWorker | Don't block the event loop in C++ |
| Reuse Buffers | Avoid copies via Napi::Buffer |
10. Alternatives (WebAssembly)
| Option | Pros |
|---|---|
| WASM | Sandboxed, portable, no rebuild per platform |
| WASI | System-call interface for WASM |
| Tools | Emscripten, AssemblyScript, wasm-pack (Rust) |