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)