介绍
插件是用 C++ 编写的动态链接共享对象。 require() 函数可以将插件加载为普通的 Node.js 模块。 插件提供了 JavaScript 和 C/C++ 库之间的接口
实现方式
[nan](https://github.com/nodejs/nan):[Node-API](https://nodejs.org/api/n-api.html)[node-addon-api](https://github.com/nodejs/node-addon-api)N-API
需要先安装 node-gyp yarn global add node-gyp
- package.json 安装 node-addon-api 和 bindings ```html { “name”: “hello_world”, “version”: “0.0.0”, “description”: “Node.js Addons Example #1”, “main”: “hello.js”, “private”: true, “dependencies”: { “bindings”: “~1.2.1”, “node-addon-api”: “^1.0.0” }, “scripts”: { “test”: “node hello.js”, “build”: “node-gyp rebuild” }, “gypfile”: true }
3. C++ 代码```cpp#include <napi.h>/*** 定义 Hello 方法* @param info* @return*/String Hello(const Napi::CallbackInfo &info) {Napi::Env env = info.Env();return Napi::String::New(env, "world");}Object Init(Env env, Object exports) {// 导出 Hello 方法为 helloexports.Set(String::New(env, "hello"), Napi::Function::New(env, Hello));return exports;}NODE_API_MODULE(hello, Init)
binding.gyp 指定需要编译的文件
{"targets": [{"target_name": "hello", // 定义文件名"cflags!": [ "-fno-exceptions" ],"cflags_cc!": [ "-fno-exceptions" ],"sources": [ "hello.cc" ], // 待编译文件"include_dirs": [ // 依赖的头文件路径,暴露给 sources 内的文件"<!@(node -p \"require('node-addon-api').include\")"],'defines': [ 'NAPI_DISABLE_CPP_EXCEPTIONS' ],}]}
node-gyp 编译出 .node 文件,可以直接再 js 中 require
node-gyp configure node-gyp build # 或者直接 node-gyp rebuildJavaScript 代码
var addon = require('bindings')('hello'); console.log(addon.hello()); // 'world'参考
