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

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

基于node-addon-api

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

hello_world.cc

1
2
3
4
5
6
7
8
9
10
11
12
13
#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

1
2
3
4
5
6
7
8
{
"targets": [
{
"target_name": "hello_world",
"sources": [ "hello_world.cc" ]
}
]
}

index.js

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

console.log(binding.hello());

package.json

1
2
3
4
5
6
...  
"scripts": {
"build": "node-gyp configure && node-gyp build",
"run:demo": "node index.js"
},
...

整体结构

按照如下命令依次运行:

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

输出如下:

1
2
3
4
5
6
D:\Projects\node-addon-demo>npm run run:demo

> [email protected] run:demo
> node index.js

world

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