我正在尝试安装node_mouse,当我查看我的node modules文件夹而不是普通的.js文件扩展名时,我找到了一个.node文件扩展名。我怎么能运行node_mouse?我查了一下,我认为它可能是用C ++编写的插件,但我不确定(Node addons)
答案 0 :(得分:3)
是的,正常的“require”用法适用于.node文件。这些文件的目的是创建可移植的二进制文件(使用来自C ++的node-gyp),可以像普通节点一样引用。请参阅node addon docs:
的hello.js部分const addon = require('./build/Release/addon');
console.log(addon.hello());
在查看这个NPM lib之后,它在我的Windows,Mac和Linux VM上正确地加载了几个不同的节点版本,但二进制文件会抛出一系列错误。在Windows上,它有一个特定版本的Windows作为构建目标(可能是NT,因为Windows 10会抛出错误):
Error: %1 is not a valid Win32 application.
在OS X上,这是dyld无法打开二进制引用的共享库。 (见man dlopen):
Error:dlopen(/.../node_mouse/node_mouse.node, 1): no suitable image found.
在Linux上,我们收到一个ELF头错误,它告诉我们二进制文件无法在此操作系统上运行。
Error: /app/available_modules/1484064894000/node_mouse/node_mouse.node: invalid ELF header
author似乎做了很多Windows NT的工作,所以如果你真的需要这个工作,找一个带有所有dev添加的Windows NT的全新副本。
最后,考虑在代码库中运行第三方封闭源二进制文件的安全风险(尤其是控制鼠标移动的二进制文件)。
答案 1 :(得分:1)
Yep these .node files are Node Addons (binary modules) and you should be able to just use require()
on them. Be aware that it will look for .json
and .js
files first.
From the documentation:
The filename extension of the compiled Addon binary is .node (as opposed to .dll or .so). The require() function is written to look for files with the .node file extension and initialize those as dynamically-linked libraries.
When calling require(), the .node extension can usually be omitted and Node.js will still find and initialize the Addon. One caveat, however, is that Node.js will first attempt to locate and load modules or JavaScript files that happen to share the same base name. For instance, if there is a file addon.js in the same directory as the binary addon.node, then require('addon') will give precedence to the addon.js file and load it instead.
You should also be aware that these are binary modules, so loading them is a lot like just running a standard executable file (Think .exe
file if you are just familiar with Windows). Like native executables they are a lot more dependent on the particulars of your system and also potentially a security risk. While a standard .js
module will be portable (with a few caveats) a .node
binary module will be fundamentally built for a particular machine architecture and OS and often even a particular version of Node. If you are having trouble loading a binary module you should make sure you are running the right version for your system, and confirm with the provider that your system is actually supported.
Sometimes specific functionality or performance needs requires it but with Node.js you shouldn't be loading binary modules unless you really have to.