Node.js C++ Addons
TL;DR
C++ Addons are dynamically-linked shared objects written in C++ that can be loaded into Node.js using the require() function, just like ordinary Node.js modules. They provide an interface between JavaScript running in V8 and native C/C++ libraries.
Mental Model
How It Works
Sometimes JavaScript is not fast enough for extreme CPU-bound tasks (like video encoding or complex cryptography), or you need to access hardware APIs that Node.js doesn’t expose.
You write the logic in C++, compile it into a .node file using node-gyp, and then require it in JavaScript.
Modern addons are written using Node-API (formerly N-API). Node-API is an ABI-stable C API provided by Node.js. “ABI-stable” means that an addon compiled for Node.js version 14 will continue to work perfectly on Node.js version 20 without needing to be recompiled!
Example
// hello.cc (C++ Side)
#include <node_api.h>
// A simple C++ function that returns "Hello World"
napi_value Method(napi_env env, napi_callback_info info) {
napi_value greeting;
napi_create_string_utf8(env, "Hello World from C++!", NAPI_AUTO_LENGTH, &greeting);
return greeting;
}
// ... Initialization boilerplate ...
// app.js (JavaScript Side)
// The compiled output is a .node file
const addon = require('./build/Release/hello.node');
console.log(addon.hello()); // Prints: "Hello World from C++!"
Common Interview Questions
When should you use a C++ addon over Worker Threads?
Worker Threads are best for parallelizing JavaScript CPU tasks. However, if the operation requires a highly optimized C/C++ library (like OpenCV for image processing, or SQLite for databases), or requires deep low-level OS access, a native addon is required.
What is node-gyp?
node-gyp is the standard cross-platform command-line tool written in Node.js for compiling native addon modules for Node.js. It wraps Google’s gyp build tool and requires Python and a C++ compiler (like GCC or Visual Studio) to be installed on the machine.