C++编译为nodejs的编译工具node-gyp

190 阅读1分钟

C++编译为nodejs的编译工具node-gyp

概述

node-gyp 是一个 Node.js 模块,用于编译 Node.js C++ 插件。它提供了一个命令行工具,可以编译 C++ 代码并将其编译为 Node.js 模块。

安装

sudo npm install -g node-gyp

demo示例

  1. 在addon.cc文件中编写C++代码,例如:
#include <node.h>
#include <iostream>

namespace demo {

using v8::FunctionCallbackInfo;
 using v8::Isolate;
 using v8::Local;
 using v8::Object;
 using v8::String;
 using v8::Value;
 using v8::Number;
 using v8::MaybeLocal;

void Method(const FunctionCallbackInfo<Value>&amp; args) {

Isolate* isolate = args.GetIsolate();
 if (args.Length() > 0 &amp;&amp; args[0]->IsString()) {
 std::cout << "123" << std::endl;
 Local<String> str = args[0].As<String>();
 args.GetReturnValue().Set(str);
 } else {
 std::cout << "678" << std::endl;
 MaybeLocal<String> maybeStr = String::NewFromUtf8(isolate, "Hello World");
 Local<String> str;
 str = maybeStr.ToLocalChecked();
 args.GetReturnValue().Set(str);
 }

// 是数字的处理方式
 // if (args.Length() > 0 &amp;&amp; args[0]->IsNumber()) {
 // int num = args[0].As<Number>()->Value();
 // args.GetReturnValue().Set(num);
 // } else {
 // args.GetReturnValue().Set(0);
 // }
 }

void init(Local<Object> exports) {
 NODE_SET_METHOD(exports, "hello", Method);
 }

NODE_MODULE(addon, init);

}

2. 编写 binding.gyp 文件

{
 "targets": [
 {
 "target_name": "addon",
 "sources": [ "addon.cc" ]
 }
 ]
}

3. 配置编译环境 在命令行中进入项目根目录,执行以下命令:

node-gyp configure // Generates a Makefile for the current module

4. 编译插件 在命令行中进入项目根目录,执行以下命令:

node-gyp build // Invokes `make` and builds the module

6. 在Node.js中使用插件 在 Node.js 中使用以下代码加载插件:

const addon = require('./build/Release/addon.node');
console.log(addon.hello()); // Hello World

7. 测试验证 node test.js