Node.js C/C++ N-Api примеры

Материал из support.qbpro.ru

Источник, на данной странице выдержки только про N-Api

1 hello world

hello.cc

#include <node_api.h>
#include <assert.h>

napi_value Method(napi_env env, napi_callback_info info) {
  napi_status status;
  napi_value world;
  status = napi_create_string_utf8(env, "world", 5, &world);
  assert(status == napi_ok);
  return world;
}

#define DECLARE_NAPI_METHOD(name, func)                          \
  { name, 0, func, 0, 0, 0, napi_default, 0 }

void Init(napi_env env, napi_value exports, napi_value module, void* priv) {
  napi_status status;
  napi_property_descriptor desc = DECLARE_NAPI_METHOD("hello", Method);
  status = napi_define_properties(env, exports, 1, &desc);
  assert(status == napi_ok);
}

NAPI_MODULE(hello, Init)

binding.gyp

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

package.json

{
  "name": "hello_world",
  "version": "0.0.0",
  "description": "Node.js Addons Example #1",
  "main": "hello.js",
  "private": true,
  "dependencies": {
    "bindings": "~1.2.1"
  },
  "scripts": {
    "test": "node hello.js"
  },
  "gypfile": true
}

hello.js

var addon = require('bindings')('hello');

console.log(JSON.stringify(addon)); // 'world'
console.log(addon.hello()); // 'world'