使用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 @   w4ngzhen  阅读(441)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示