环境及问题解决
1,node-gyp:9.0.0
2,node:14.0.0
3,python:3.10.5
4,vs_buildTools
node-gyp@9.0.0需要python版本在3.7.x以上,否则会提示你需要更新到最新版本的python。
node版本选择14.0.0是因为,我开始使用的是10.10.0版本,但是会爆出一个错误,TypeError: Object.fromEntries is not a function
。选择14.0.0之后解决了这个问题。
vs build tools的安装,有两种方式。
1,运行命令:npm install --global --production windows-build-tools
,但是我当时会卡主不动,并且安装的python是2.7.x的版本不符和要求(如果你提前安装了python3.7.x以上版本则没问题)。
2,安装vs2017,安装时还需要选择以下工具,并安装(我选择的方式)
测试用例:
选择一个文件夹,在该位置打开控制台,输入 npm init -y
;
安装npm i node-addon-api --save
1,创建hello.cc文件,并写入
#include <napi.h>
#include <stdio.h>
using namespace Napi;
String Hello(const CallbackInfo& info) {
return String::New(info.Env(), "Hello world");
}
Napi::Object Init(Env env, Object exports) {
exports.Set("hello", Function::New(env, Hello));
return exports;
}
NODE_API_MODULE(addon, Init)
2,创建bingding.gyp文件,并写入
{
"targets": [
{
"target_name": "hello",
"sources": [
"hello.cc"
],
"include_dirs": [
"<!@(node -p \"require('node-addon-api').include\")"
],
"dependencies": [
"<!(node -p \"require('node-addon-api').gyp\")"
],
"cflags!": ["-fno-exceptions"],
"cflags_cc!": ["-fno-exceptions"],
"defines": ["NAPI_CPP_EXCEPTIONS"],
"xcode_settings": {
"GCC_ENABLE_CPP_EXCEPTIONS": "YES"
}
}
]
}
3,创建index.js文件,并写入
const hello = require('./build/Release/hello.node');
console.log(hello.hello());
文件目录如下:
运行
node-gyp configure
node-gyp build
node index.js