使用 callbackInfo 在 linux 上运行 Napi 的问题

问题描述

当使用 Windows 时,我和 Napi 运行 npm i 它编译并且工作得很好。在 linux 上做同样的事情时,我收到了 napi-inl.h 的这个错误

project/node_modules/node-addon-api/napi-inl.h: In instantiation of ‘static Napi::Function Napi::Function::New(napi_env,Callable,const char*,void*) [with Callable = Napi::Promise (*)(Napi::CallbackInfo&); napi_env = napi_env__*]’:
../test.cc:10:50:   required from here
project/node_modules/node-addon-api/napi-inl.h:1985:22: error: cannot bind non-const lvalue reference of type ‘Napi::CallbackInfo&’ to an rvalue of type ‘Napi::CallbackInfo’
 1985 |   typedef decltype(cb(CallbackInfo(nullptr,nullptr))) ReturnType;
      |                    ~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
project/node_modules/node-addon-api/napi-inl.h:1985:22: error: cannot bind non-const lvalue reference of type ‘Napi::CallbackInfo&’ to an rvalue of type ‘Napi::CallbackInfo’
project/node_modules/node-addon-api/napi-inl.h:1996:5: error: type ‘<type error>’ argument given to ‘delete’,expected pointer
 1996 |     delete callbackData;
      |     ^~~~~~

test.cc 看起来像这样

#include <napi.h>
#include "processData.h"


// This is were the Node module function name is assigned
// when imported getData() will be the function to call
// It calls Process()
Napi::Object Init(Napi::Env env,Napi::Object exports) {
  exports.Set(Napi::String::New(env,"getData"),Napi::Function::New(env,Process));
  return exports;
}

NODE_API_MODULE(NODE_GYP_MODULE_NAME,Init)

我不知道这是我的问题还是 NAPI 的问题

解决方法

发现问题是一个简单的错误,涉及 Process.cc 中的函数声明缺少 const 关键字

老方法:

Napi::Promise Process(Napi::CallbackInfo& info)

新方法:

Napi::Promise Process(const Napi::CallbackInfo& info)
,

这是因为 npm i 在 Windows 和 Linux 上是不同的。引用对another question的回答:

是的,可能存在差异,例如,如果您(或您的依赖项)使用原生 node.js 插件,这些插件是构建的,例如通过 node-gyp 并包含本机二进制代码。在 package.json 中也可以有 OS/CPU 特定的东西。 package.json 说明可以在这里找到:https://docs.npmjs.com/files/package.json