在编写Node插件之前我们首先要了解一下node.js插件的编写方式, 我们今天采用的是三种方式之一的 Node-Api进行编写,采用C++实现,根据下面步骤你也可以编写自己的插件。
但是编写插件需要有C/C++基础,如果没有基础那么建议忽略本文。
环境准备
Python 3.x环境
Node.js 15.x+
gcc 8.2.x /VC2022
MacOS /Windows
编写代码
创建插件文件夹,并创建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",
"node-addon-api": "^1.0.0"
},
"scripts": {
"test": "node hello.js"
},
"gypfile": true
}
同目录创建hello.cc插件源码文件,内容如下
#include <napi.h>
Napi::String Method(const Napi::CallbackI