在电子中调用节点本地插件(C ++)

我对Node JS和Electron完全陌生。 我正在尝试使用Electron和Node JS将C ++与HTML集成。 我已经通过一些例子给出了: GIT

我想要做的是从我的网页的JavaScript电子加载调用本地函数(你好())。 我已经使用node-gyp configure来生成我的Visual Studio解决scheme文件。 ( .sln )。 之后,我使用Visual Studio 2013 Express编译了我的代码,在build \ Release文件夹中成功生成了我的.node文件。

这是我的index.js文件:

 var addon = require('./build/Release/hello.node'); console.log(addon.hello()); 

当我简单地运行这个node index.js ,它给我所需的输出:

 world 

但是当我使用电子时,问题就出现了。 我使用电子二进制(32位)来运行我的网页。

以下是我的main.js文件:

 var app = require('app'); // Module to control application life. var BrowserWindow = require('browser-window'); // Module to create native browser window. require('crash-reporter').start(); var mainWindow = null; // Quit when all windows are closed. app.on('window-all-closed', function() { if (process.platform != 'darwin') { app.quit(); } }); // This method will be called when Electron has finished // initialization and is ready to create browser windows. app.on('ready', function() { mainWindow = new BrowserWindow({width: 1366, height: 768}); mainWindow.loadUrl("file://" + __dirname + "/HtmlFile/index.html"); mainWindow.on('closed', function() { mainWindow = null; }); }); 

现在这是我的JavaScript调用本地插件:

 //************* My Functional logic ************** //************************************************ var addon = require('../build/Release/hello'); alert(addon.hello()); 

当我运行这个或加载此页面,我收到以下错误:

 Uncaught Error: %1 is not a valid Win32 application. ATOM_SHELL_ASAR.js:137 C:\Users\Administrator\Desktop\MyAPP\build\Release\hello.node 

以下是我的package.json

 { "name": "MyAPP", "version": "1.0.0", "description": "Desc", "main": "main.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC", "dependencies": { "nan": "^2.0.9" }, "gypfile": true } 

这是我的binding.gyp

 { "targets": [ { "target_name": "hello", "sources": [ "hello.cc" ], "include_dirs": [ "<!(node -e \"require('nan')\")" ] } ] } 

看起来你可能没有configuration正确的二进制文件。 对不起,不知道这是否适用于本地模块,但你可以尝试重build …

注意:请确保你有你的node-gyp命令的正确参数(如果这是你将重build)。

  • --target=<your electron version>
  • --target_platform=win32 (不是在示例链接,但你似乎正在使用Windows)
  • --arch=<your architecture> (x64 = 64bit,x86 = 32bit)

正如我在评论中提到的那样,我遇到了同样的问题。 要解决它,你需要添加一些额外的标志:

 node-gyp rebuild --target=<your electron version> --arch=<insert your arch> --dist-url=https://atom.io/download/atom-shell 

这将从atom.io站点获得正确的要求,并正确地构build附加组件。 欲了解更多信息,您可以检查使用本机模块电子的具体文档 。

关于本地插件中节点和电子标题的个人问题需要一个不同的dist-url参数值:

  --dist-url=https://atom.io/download/electron 

希望它能帮助别人。

PS:仍然无法弄清楚如何在Windows中使用.npmrc来设置它(

直接使用node-gyp将使用nodejs头来构build,但是电子具有不同的头部。

首先你应该弄清楚电子版电子正在使用。 你可以写一个像这样的js

 console.log(process.version); 

使用电子执行这个脚本,我的版本是0.36.1,并改变目录到你想要build立的模块

 #On Windows Try this cd /path-to-module/ npm install bindings nan node-gyp node-gyp rebuild --target=0.36.1 --arch=x64 --dist- url=https://atom.io/download/atom-shell #notice the target version is the electron binary version