1.环境搭建
npm init
npm i --save --dev node-gyp node-addon-api
在package.json中加入如下配置:
在package.json同级目录下创建配置文件binding.gyp:
{
"targets": [{
"target_name": "helloworld",
"cflags!": [ "-fno-exceptions" ],
"cflags_cc!": [ "-fno-exceptions" ],
"sources": [
"cppsrc/helloworld.cpp"
],
"include_dirs": [
"<!@(node -p \"require('node-addon-api').include\")"
],
"libraries": [],
"dependencies": [
"<!(node -p \"require('node-addon-api').gyp\")"
],
"defines": [ 'NAPI_DISABLE_CPP_EXCEPTIONS' ]
}]
}
在package.json同级目录下创建文件夹cppsrc,接下来就可以开始开发了
2.Hello World
helloworld.cpp
#include <string>
#include <stdio.h>
#include <napi.h>
using namespace Napi;
void HelloWorld(const CallbackInfo& info) {
Env env = info.Env();
// 检查参数
if (info.Length() < 1 || !info[0].IsString()) {
TypeError::New(env, "Invalid parameter, helloWorld(name: string).")
.ThrowAsJavaScriptException();
}
std::string name = info[0].As<String>().Utf8Value();
printf("%s says: Hello, World!\n", (char*)name.c_str());
return;
}
Object Initialize(Env env, Object exports) {
exports.Set("MOD_ID", Number::New(env, 1399));
exports.Set("helloWorld", Function::New(env, HelloWorld));
return exports;
}
NODE_API_MODULE(NODE_GYP_MODULE_NAME, Initialize)
接下来进行编译,需要注意,旧版本node包括v10.x.x的node_gyp是py2版本、不兼容py3的,你可能需要用Anaconda创建一个虚拟环境:
npm run build
如果编译通过,那我们可以在nodejs调用这个addon了:
const lib = require('./build/Release/helloworld.node')
lib.helloWorld('Mr Li')
console.log(lib.MOD_ID)
运行结果:
3.参考资料
这篇文章只能帮助你完成node addon开发环境的搭建以及基本了解node addon的结构。
在实际开发过程中,你可能需要深入学习node-addon-api的API:Github: node-addon-api。
这里有一篇文章更详细的介绍了如何使用node-addon-api,但需要翻墙:🤖 Beginners guide to writing NodeJS Addons using C++ and N-API (node-addon-api)