介绍

插件是用 C++ 编写的动态链接共享对象。 require() 函数可以将插件加载为普通的 Node.js 模块。 插件提供了 JavaScript 和 C/C++ 库之间的接口

实现方式

  1. [nan](https://github.com/nodejs/nan):
  2. [Node-API](https://nodejs.org/api/n-api.html)
  3. [node-addon-api](https://github.com/nodejs/node-addon-api)

    N-API

  4. 需要先安装 node-gyp yarn global add node-gyp

  5. 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 }
  1. 3. C++ 代码
  2. ```cpp
  3. #include <napi.h>
  4. /**
  5. * 定义 Hello 方法
  6. * @param info
  7. * @return
  8. */
  9. String Hello(const Napi::CallbackInfo &info) {
  10. Napi::Env env = info.Env();
  11. return Napi::String::New(env, "world");
  12. }
  13. Object Init(Env env, Object exports) {
  14. // 导出 Hello 方法为 hello
  15. exports.Set(String::New(env, "hello"), Napi::Function::New(env, Hello));
  16. return exports;
  17. }
  18. NODE_API_MODULE(hello, Init)
  1. binding.gyp 指定需要编译的文件

    1. {
    2. "targets": [
    3. {
    4. "target_name": "hello", // 定义文件名
    5. "cflags!": [ "-fno-exceptions" ],
    6. "cflags_cc!": [ "-fno-exceptions" ],
    7. "sources": [ "hello.cc" ], // 待编译文件
    8. "include_dirs": [ // 依赖的头文件路径,暴露给 sources 内的文件
    9. "<!@(node -p \"require('node-addon-api').include\")"
    10. ],
    11. 'defines': [ 'NAPI_DISABLE_CPP_EXCEPTIONS' ],
    12. }
    13. ]
    14. }
  2. node-gyp 编译出 .node 文件,可以直接再 js 中 require

    node-gyp configure
    node-gyp build
    # 或者直接 node-gyp rebuild
    
  3. JavaScript 代码

    var addon = require('bindings')('hello');
    console.log(addon.hello()); // 'world'
    

    参考

  4. node-addon-api 示例