Uncaught Error : error 1114 in electron

Uncaught Error : error 1114 in electron

我正在使用本机 C++ 在 electron 上制作一个简单的 hello world 应用程序,但收到此 Uncaught Error : error 1114 错误。当项目在 Windows 上运行时会出现此错误,而在 Fedora 上运行良好。

package.json:

{
    "name": "nodec",
    "version": "1.0.0",
    "description": "",
    "main": "index.js",
    "scripts": {
        "start": "electron ."
    },
    "author": "",
    "license": "ISC",
    "devDependencies": {
        "electron-packager": "^8.7.0"
    }
}

binding.gyp:

{
    "targets": [
        {
            "target_name": "addon",
            "sources": [ "addon.cc" ]
        }
    ]
}

addon.cc:

#include <node.h>
namespace demo {
using v8::Exception;
using v8::FunctionCallbackInfo;
using v8::Isolate;
using v8::Local;
using v8::Number;
using v8::Object;
using v8::String;
using v8::Value;

void hello(const FunctionCallbackInfo& args) {
Isolate* isolate = args.GetIsolate();

args.GetReturnValue().Set(String::NewFromUtf8(isolate,"world"));
}

void Init(Local exports) {
NODE_SET_METHOD(exports, "hello", hello);
}

NODE_MODULE(addon, Init)
}

main.js:

const addon = require('./build/Release/addon');
console.log('This should be eight:', addon.hello());

index.html:

<title>My C++ App</title> Hello <script> require('./main.js') </script>

我已经多次配置和构建项目,但在这种情况下似乎没有帮助。

首先,你的代码有几个缺陷:

  • addon.cc: FunctionCallbackInfoLocal 必须有模板参数。更正后的函数签名为:
void hello(const FunctionCallbackInfo<Value>& args)
void Init(Local<Object> exports)
  • package.json:你的切入点应该是
"main": "main.js",

其次,您必须按照 guide 中的描述专门针对 electron 构建您的插件。例如,将其构建到最新的 electron 版本 (1.4.13) 使用以下命令:

node-gyp configure build --target=1.4.13 --arch=x64 --dist-url=https://atom.io/download/electron

--arch根据你的平台标记)

所有这些之后,它运行成功

npm run start

打印This should be eight: world到控制台


由于您没有在代码中的任何地方使用 index.html - 尽管您的目标可能是在那里打印 - 您可以尝试这些改进的 main.jsindex.html:

const { app, BrowserWindow } = require('electron')
const path = require('path')

app.once('ready', () => {
  new BrowserWindow().loadURL(path.join(__dirname, 'index.html'))
})
<html>
  <head>
    <title>My C++ App</title>
  </head>
  <body>
    <div>
      <h1>
        Hello 
        <script>document.write(require('./build/Release/addon').hello())</script>
      </h1>
    </div>
  </body>
</html>

结果在浏览器中显示 Hello world window