簡體   English   中英

使用 C++ 插件為 nodejs 應用程序構建獨立的可執行文件

[英]Building a standalone executable for nodejs application with C++ addons

我目前正在為nodejs構建C++插件,以便我可以通過websockets公開一些C++ API。 這個 API 讓客戶端可以與連接到 PC(甚至是 Pi)的復合設備通信。 由於它將部署在 PC 上,因此我想將其捆綁為獨立應用程序。 我已經為 POC 使用了 node webkit (nw + nw-gyp)。 這工作得很好,但是向前推進我想將 UI 層分解為單獨的可部署層,並將 websockets API 暴露為單獨的可部署層。

但是目前,當您使用 node-webkit 構建應用程序時,它還包括瀏覽器,這使得“大”可部署。 我真的不需要包含瀏覽器。 無論如何要說節點 webkit 不包括瀏覽器? 我已經將 jxcore 視為一種可能的替代方案,但它仍然是一個非常年輕的項目,我不確定它是否也可以支持 C++ 插件。 有沒有更好的方法來構建具有本機插件作為依賴項的獨立節點應用程序(沒有 UI)?

一個更簡單的解決方案是在瀏覽器中使用 web 組件,在網絡上使用 JRPC(但抽象對象)。 Nodejs 可以使用 SWIG 連接 C++,從而關閉瀏覽器和 C++ 之間的循環。

這種方法避免使用繁重的框架和依賴項。

此微應用中提供了一個完整的示例。 它的基礎是使用 SWIG 包裝您的 C++ 以便 nodejs 可以要求它:

%module "swigCNodejs"
%{
#include "Test.H"
%}

%include <std_string.i>
%include "Test.H"

然后將該包裝器編譯為在 nodejs 中執行的 nodejs 模塊,如下所示:

var libSwigCNodejs = require('../swig/.libs/libSwigCNodejs');
let test = new libSwigCNodejs.Test;

使用 JRPC+JRPC-OO 通過網絡將 class 暴露給瀏覽器:

let JRPCTools = require('@flatmax/jrpc-oo/JRPCTools');

// get a class to expose over the network
let TestClass = require('./TestClass').TestClass;

// note TestClass2 inherits TestClass
tc=new TestClass; // this class will be used over js-JRPC

// start the server and add the class.
var JrpcServer=new JRPCTools.JRPCServer(9000); // start a server on port 9000
JrpcServer.addClass(tc); // setup the class for remote use over the network

然后在瀏覽器中實現你的 webcomponent 來繼承 JRPCClient class ,如下所示:

class Test extends JRPCClient {...};

您現在可以通過網絡從瀏覽器執行 C++。

如果您構建了 Node.js 擴展/插件,並且您不需要瀏覽器來進行包裝,那么您為什么要使用 NW.js? 如果您只是想將 Node.js 腳本轉換為 EXE,請使用pkg ( https://www.npmjs.com/package/pkg )。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM