使用自定义 nodejs 插件时的"The specified module could not be found"

"The specified module could not be found" when using a custom nodejs addon

本文关键字:module specified could not found be The nodejs 自定义 插件      更新时间:2023-10-16

我正在编写一个依赖于OpenGL(glfw(的nodejs插件。它编译成功,但是当我尝试在节点中使用它时,我收到错误The specified module could not be found

这是插件C++代码中存在问题的部分:

#include <glfw/glfw3.h>
if(glfwInit()) {
printf("glfw init success");
}
else {
printf("glfw init failed");
}

在插件中使用它,它可以编译但在节点中导致错误。没有这个,它可以编译和运行没有问题。

这是我的绑定.gyp:

{
"targets": [
{
"target_name": "engine",
"sources": [
"addon/addon.cc"
],
"libraries": [
"<(module_root_dir)/addon/lib/gl/glfw3dll.lib"
],
"include_dirs": [
"addon/lib",
"<!@(node -p "require('node-addon-api').include")"
],
'defines': [ 'NAPI_DISABLE_CPP_EXCEPTIONS' ],
}
]
}

和插件文件结构:

addon
lib
glfw
glfw3.dll
glfw3.h
glfw3.lib
glfw3dll.lib
glfw3native.h
opengl32.lib
addon.cc

编辑: New binding.gyp:

{
"targets": [
{
"target_name": "engine",
"sources": [
"addon/addon.cc"
],
"libraries": [
"-lglfw3dll",
"-lopengl32",
"-L<module_root_dir)/lib/glfw",
"-Wl,-rpath,$$ORIGIN/../../lib",
],
"include_dirs": [
"addon/lib",
'<!@(node -p "require('node-addon-api').include")'
],
'defines': [ 'NAPI_DISABLE_CPP_EXCEPTIONS' ],
}
]
}

我不确定这是您的问题,但说服加载程序在本地目录中加载特定库可能有点棘手。我将此部分添加到 binding.gyp 中的targets数组中。

诀窍是告诉链接器相对于$ORIGIN(插件所在的位置(查找库。因为插件在build/Release所以$ORIGINbuild/Release../../让你回到模块根目录。

只是需要反复试验才能找到通过binding.gyp和链接器的引用规则指定$ORIGIN的正确方法。$$ORIGIN导致$ORIGIN嵌入到节点插件中。

'conditions': [
['OS in "linux"', {
# includes reference glfw3dll/glfw3dll.h, so
'include_dirs': [
'<!@(node -p "require('node-addon-api').include")',
'<(module_root_dir)/'
],
'libraries': [
'-lglfw3dll',
'-L<(module_root_dir)/dir-for-glfw3dll/',
'-Wl,-rpath-link,<(module_root_dir)/dir-for-glfw3dll/',
'-Wl,-rpath,$$ORIGIN/../../dir-for-glfw3dll/'
],
}]
]

(我将文件的名称更改为您的文件,并将其放在module_root_dir正下方的目录中。

我设法让它与这个binding.gyp文件一起工作:

{
"targets": [
{
"target_name": "engine",
"sources": [
"addon/addon.cc"
],
"libraries": [
"legacy_stdio_definitions.lib",
"msvcrt.lib",
"msvcmrt.lib",
"<(module_root_dir)/addon/lib/glfw/opengl32.lib",
"<(module_root_dir)/addon/lib/glfw/glfw3.lib"
],
"include_dirs": [
"addon/lib",
'<!@(node -p "require('node-addon-api').include")',
],
'defines': [ 'NAPI_DISABLE_CPP_EXCEPTIONS' ]
}
]
}

以防其他人遇到同样的问题并最终来到这里。插件所需的库需要在运行时触手可及,即使链接器设法找到了它。

例如,如果这是在Windows上,并且在运行时构建/链接期间与foo.lib链接,则foo.dll应该位于同一文件夹中(对我来说,它与.node在同一个文件夹中(或在路径中的文件夹中。否则,它不会被加载,并且将引发此错误。在我看来非常无法解释的错误。

此外,将库保存在与 .node 相同的文件夹中有助于隔离不同的 arch 构建和依赖项(x86、x64 等(。

相关文章: