用 C++ 写一个 nodejs addon。
我的系统是 MacOS 10.15.7。
一、安装 node-gyp
我是全局安装。
npm i node-gyp -g
注意:node-gyp 依赖 Python 和 Xcode Command Line Tools,详细信息请参考:https://github.com/nodejs/node-gyp
二、写 bindding.gyp
{
  "targets": [
    {
      "target_name": "addon",
      "sources": [ "hello.cc" ]
    }
  ]
}
三、编写 hello.cc
#include <node.h>
namespace demo
{
  using v8::FunctionCallbackInfo;
  using v8::Isolate;
  using v8::Local;
  using v8::Object;
  using v8::String;
  using v8::Value;
  void Method(const FunctionCallbackInfo<Value> &args)
  {
    Isolate *isolate = args.GetIsolate();
    // 返回一个字符串 world
    args.GetReturnValue().Set(String::NewFromUtf8(
                                  isolate, "world")
                                  .ToLocalChecked());
  }
  // 初始化,接收一个 exports 对象
  void Initialize(Local<Object> exports)
  {
    // 在 exports 上导出一个方法,方法名是 hello,方法的实现是 Method
    NODE_SET_METHOD(exports, "hello", Method);
  }
  // NODE_MODULE 是宏。用来初始化一个 nodejs 模块
  NODE_MODULE(NODE_GYP_MODULE_NAME, Initialize)
}
四、配置和编译
配置
node-gyp configure
编译
// 默认编译输出的目录是 build/Release
node-gyp build
// 如果遇到错误,可以尝试
node-gyp rebuild
五、nodejs 调用 .node
// demo.js
const addon = require("./build/Release/addon");
console.log(addon.hello()); // 输出 world