Node.js 为什么我们需要使用C++插件
在本文中,我们将看到为什么我们需要在Node.js中使用C++插件。
- Node.js插件是用C++编写的动态链接共享对象。
- 可以使用require()函数将其加载到Node.js中,并且可以像普通的Node.js模块一样使用。
- 它主要用于提供JavaScript在Node.js中与C/C++库之间的接口。
为什么我们需要C++插件?
- 它提供了进行密集、并行和高精度计算的机会。
- 它还提供了在Node.js中使用C++库的机会。
- 我们可以集成一个用C/C++编写的第三方库,并直接在Node.js中使用它。
- C++在处理较大的值或计算时性能优于其他语言。
先决条件:
- 基本的Node知识。
- 已安装Node.js(版本12以上)。
- 已安装Npm(版本6以上)。
模块安装: 使用以下命令安装所需模块。
npm i -g node-gyp
文件夹结构:
它的样子会是这样的。
现在创建binding.gyp、calculate.cc文件,并使用以下代码:
文件名: binding.gyp
{
"targets": [
{
"target_name": "calculate", // Name of C++ Addons.
"sources": [ "calculate.cc" ] // Source of C++ file.
}
]
}
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);
}
app.js
// Require addons
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');
运行应用程序的步骤: 要构建和配置,请运行以下命令。
node-gyp configure build
node app.js
输出:
c++: 1.184s
js: 1.207s