node-gyp环境配置报错处理,nodejs 调用 c++接口

环境及问题解决

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
在这里插入图片描述

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值