1. 環境安裝
a. 安裝 nodejs (https://blog.csdn.net/yt_php/article/details/90105880)
b. cnpm install -g node-gyp // cnpm 的安裝 npm install -g cnpm --registry=https://registry.npm.taobao.org
2. binding.gyp 文件編寫
該文件不能注釋,下列注釋為例說明,實際編譯需要取消
{ "targets": [ { "target_name": "js_login", "sources": [ "js_login.cpp" ], 'conditions': [ [ 'OS=="win"', { 'include_dirs': [], 'sources':[], 'msvs_settings': {}, 'link_settings': { 'libraries': [ '../login.lib' // 工程文件為起點的相對路徑,工程文件在 node-gyp configure 后會生成 ] } } ], [ 'OS=="linux"', { 'ldflags':["-Wl,-rpath,'$$ORIGIN'"], 'cflags!':['-Wignored-attributes'], 'cflags':['-lrt'], 'cflags_cc': ['-frtti', '-fPIC', '-fexceptions', '-lrt'], 'link_settings': { 'libraries': [ '-llogin' ], 'library_dirs': [ '/home/vrv3/work/electron/ddm_7/logindll', // 庫搜索路徑 ], } } ] ] } ] }
3. js_login.cpp 編寫
#include <stdio.h> #include <stdlib.h> #include <node.h> #include "./logindll/src/login.h" using v8::FunctionCallbackInfo; using v8::Isolate; using v8::Local; using v8::Object; using v8::String; using v8::Value; void login(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = args.GetIsolate(); Local<String> account = Local<String>::Cast(args[0]); String::Utf8Value utfaccount(account); Local<String> pwd = Local<String>::Cast(args[1]); String::Utf8Value utfpwd(pwd); int result = login(std::string(*utfaccount), std::string(*utfpwd), "", 1); // 調用DLL,該方法由庫提供 char buf[10] = {'\0'}; sprintf(buf, "%d", result); Local<String> value = String::NewFromUtf8(isolate, buf); args.GetReturnValue().Set(value); } void init(Local<Object> exports) { NODE_SET_METHOD(exports, "login", login); } NODE_MODULE(LOGIN, init)
4. 編譯
sudo node-gyp configure build
5. 測試
test.js 文件
const FaceRecognition = require('./build/Release/js_login'); // js_login 指的是 js_login.node 文件,sudo node-gyp configure build 時會編譯出該文件 console.log(FaceRecognition.login("vvv", "123456"));
執行 node test.js 即可運行該測試文件
6.問題及解決過程
NODE_MOUDLE_VERSION不一致問題(node 10.11.0 electron 4.x 可以匹配)
NODE_MODULE_VERSION 指 node.js 的 ABI 版本號,是一個整數,用來確定編譯 node.js 的 C++ 庫的版本,該版本號與 Electron 版本是強匹配的,指定 Electron 版本號的編譯方法如下
sudo node-gyp rebuild --target=4.0.1 --arch=x64 --dist-url=https://atom.io/download/electron // --arch 參數去支持編譯成不同位數的addon, ia32表示32位,x64表示64位。
該操作涉及到文件下載,下載的文件在如下路徑,如果下載失敗,可以拷貝可用的文件(electron 版本)到該目錄
C:\Users\vrv\AppData\Local\node-gyp\Cache
electron-rebuild 好像也可以解決該問題
.node 文件require時候顯示Error: The specified module could not be found
第一:你要確定你的.node 是好的,然后你可以繼續下一步了
第二:你的.node發現不了可能是因為缺少了依賴關系,簡單點說,就是缺少了.dll
第三:下載 Dependency Walker,這個軟件可以幫你確定一下缺少什么.dll,下載地址:http://www.dependencywalker.com/
第四:下載完Dependency Walker 直接打開.node 文件,將提示缺少的重要.dll 放在.node 同一級的目錄下,當然你也可以不用下軟件,直接把重要的.dll放在.node目錄下就可以了。
第五:運行,就不會報錯了。
注意64與32版本
NodeJS C++ Addons基礎:
https://hongchh.github.io/2018/NodeJS-Cpp-Addons%E5%9F%BA%E7%A1%80/
參考鏈接:
https://nodejs.org/api/addons.html
https://v8docs.nodesource.com/node-11.14/
----------------------------------------------------------