Node.js and C++ get along!
Node.js addons are dynamically loadable C/C++ libraries that can be integrated with Node.js applications. They allow developers to extend the capabilities of Node.js by writing performance-critical or low-level code in a compiled language like C or C++. Node.js addons provide a bridge between JavaScript and native code, enabling developers to leverage existing libraries or write high-performance modules directly in C/C++.
Here's an example of a Node.js addon written in C++:
Create a new folder for your addon project and navigate into it:
$ mkdir myaddon
$ cd myaddon
Create a new file named calculate.cc:
#include <node.h>
#include <iostream>
namespace calculate {
using v8:: FunctionCallbackInfo;
using v8 :: Isolate;
using v8 :: Local;
using v8 :: Object;
using v8 :: Number;
using v8 :: Value;
// C++ add function.
void Sum(const FunctionCallbackInfo<Value>&args)
{
Isolate* isolate = args.GetIsolate();
int i;
double x = 3.141526, y = 2.718;
for(i=0; i<1000000000; i++)
{
x += y;
}
auto total = Number::New(isolate,x);
args.GetReturnValue().Set(total);
}
// Exports our method
void Initialize(Local<Object> exports) {
NODE_SET_METHOD(exports, "calc", Sum);
}
NODE_MODULE(NODE_GYP_MODULE_NAME,Initialize);
}
Create a new file named binding.gyp:
{
"targets": [
{
"target_name": "calculate",
"sources": [ "calculate.cc" ]
}
]
}
Open a terminal and navigate to the root folder of your addon project.
Use the node-gyp tool to configure and build the addon:
领英推荐
$ npm install -g node-gyp
$ node-gyp configure build
Create a new file named index.js:
// Require addon
const calculate = require('./build/Release/calculate');
// Javascript add function.
function calc() {
// Two variables.
let i, x = 3.141526, y = 2.718;
for (i = 0; i < 1000000000; i++) {
x += y;
}
let total = x;
return total;
}
console.time('c++');
calculate.calc();
console.timeEnd('c++');
console.time('js');
calc();
console.timeEnd('js');s
Run the Node.js script to test the addon:
$ node index.js
You should see the following output:
c++: 2.988s
js: 3.305s
In this example, we created a C++ file in which the Sum ( exported as calc ) function is executed. This runs through an intensive loop that performs a simple sum. On the other hand, in the index.js file, the calc() function performs the same process. Time is counted for each process and it is shown in the terminal once they are done.
Now you know how to import C++ code inside your Node.js app just as if you were using plain JS. How cool is that!! ????