When JavaScript's execution speed is not enough—such as in high-frequency algorithmic trading, direct IoT hardware communication, or 3D computer graphics processing—Node.js allows developers to write Native C++ Addons compiled directly into native machine code via Node-API (N-API).
binding.gyp{
"targets": [
{
"target_name": "fastmath",
"sources": [ "src/fastmath.cc" ],
"include_dirs": [
"<!@(node -p \"require('node-addon-api').include\")"
],
"dependencies": [
"<!@(node -p \"require('node-addon-api').gyp\")"
],
"cflags!": [ "-fno-exceptions" ],
"cflags_cc!": [ "-fno-exceptions" ]
}
]
}
src/fastmath.cc#include <napi.h>
// Native C++ function to add two numbers
Napi::Number FastAdd(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
double arg0 = info[0].As<Napi::Number>().DoubleValue();
double arg1 = info[1].As<Napi::Number>().DoubleValue();
Napi::Number sum = Napi::Number::New(env, arg0 + arg1);
return sum;
}
// Module initialization
Napi::Object Init(Napi::Env env, Napi::Object exports) {
exports.Set(Napi::String::New(env, "fastAdd"), Napi::Function::New(env, FastAdd));
return exports;
}
NODE_API_MODULE(fastmath, Init)
// app.js
const { fastAdd } = require('./build/Release/fastmath');
console.log('C++ Native Addon Result:', fastAdd(150.5, 349.5)); // 500
Boost your server-side JavaScript proficiency by studying these closely connected core modules:
C++ bindings bridge JavaScript to the OS.
Execute native code across worker threads.
Benchmark native C++ performance gains.