Working with Native Addons

1. Understanding N-API (Node-API)

AspectDetail
ABI stableCompiled addon works across Node versions
C APIHeader node_api.h
C++ wrappernode-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

FilePurpose
binding.gypBuild config (sources, include_dirs)
node-gyp configureGenerate platform build files
node-gyp buildCompile
node-gyp rebuildClean + configure + build

4. Building Native Modules

ToolUse
node-gypDefault
cmake-jsCMake-based
prebuildify + prebuild-installShip 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

FeatureDetail
RAII C++ wrapperAround N-API
Exception supportNapi::Error::New(env, msg).ThrowAsJavaScriptException()
Async workNapi::AsyncWorker

7. Cross-Platform Compilation

ConcernDetail
ToolchainMSVC on Windows, clang/gcc on Unix
PythonRequired by node-gyp
CI matrixBuild per (OS × arch × Node ABI)

8. Debugging Native Code

ToolUse
gdb / lldbAttach to node process
Visual StudioWindows native debugging
--abort-on-uncaught-exceptionCore dump on crash

9. Performance Considerations

TipDetail
Cross JS↔C++ boundary costBatch calls; avoid hot-loop crossings
Use AsyncWorkerDon't block the event loop in C++
Reuse BuffersAvoid copies via Napi::Buffer

10. Alternatives (WebAssembly)

OptionPros
WASMSandboxed, portable, no rebuild per platform
WASISystem-call interface for WASM
ToolsEmscripten, AssemblyScript, wasm-pack (Rust)