使用node-gyp编写简单的node原生模块

通过样例,让我们了解如何编写一个node的原生模块。当然,这篇文章还有一个目的,是为了方便以后编写关于node-gyp的文章,搭建初始环境。

基于node-addon-api

基于node-addon-api的nodejs插件,使用的是node的头文件:#include <node.h>

hello_world.cc

#include <node.h>

void Method(const v8::FunctionCallbackInfo<v8::Value>& args) {
  v8::Isolate* isolate = args.GetIsolate();
  args.GetReturnValue().Set(v8::String::NewFromUtf8(
      isolate, "world").ToLocalChecked());
}

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

NODE_MODULE(NODE_GYP_MODULE_NAME, Initialize)

binding.gyp

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

index.js

const binding = require('./build/Release/hello_world');

console.log(binding.hello());

package.json

...  
  "scripts": {
    "build": "node-gyp configure && node-gyp build",
    "run:demo": "node index.js"
  },
...

整体结构

按照如下命令依次运行:

$ npm run build
// 使用node-gyp配置并构建
$ npm run run:demo
// 运行Demo

输出如下:

D:\Projects\node-addon-demo>npm run run:demo

> node-addon-demo@1.0.0 run:demo
> node index.js

world

附上GitHub地址:w4ngzhen/node-addon-demo (github.com),方便以后快速完成环境搭建。

posted @ 2021-06-25 16:02  w4ngzhen  阅读(397)  评论(0编辑  收藏  举报