溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

怎么編寫nodejs c++插件

發(fā)布時間:2021-11-24 11:52:17 來源:億速云 閱讀:172 作者:iii 欄目:大數(shù)據(jù)

這篇文章主要介紹“怎么編寫nodejs c++插件”,在日常操作中,相信很多人在怎么編寫nodejs c++插件問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”怎么編寫nodejs c++插件”的疑惑有所幫助!接下來,請跟著小編一起來學習吧!

環(huán)境

1 ubuntu18.04。
2 安裝nodejs v12和npm install node-gyp -g。 

寫代碼

寫一個測試的例子。test.cc

// hello.cc using N-API
#include <node_api.h>

namespace demo {

napi_value Method(napi_env env, napi_callback_info args) {
  napi_value greeting;
  napi_status status;

  status = napi_create_string_utf8(env, "world", NAPI_AUTO_LENGTH, &greeting);
  if (status != napi_ok) return nullptr;
  return greeting;
}

napi_value init(napi_env env, napi_value exports) {
  napi_status status;
  napi_value fn;

  status = napi_create_function(env, nullptr, 0, Method, nullptr, &fn);
  if (status != napi_ok) return nullptr;

  status = napi_set_named_property(env, exports, "hello", fn);
  if (status != napi_ok) return nullptr;
  return exports;
}

NAPI_MODULE(NODE_GYP_MODULE_NAME, init)

}  // namespace demo
 

binding.gyp

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

然后執(zhí)行npm init。內(nèi)容如下

{
  "name": "test-addons",
  "version": "1.0.1",
  "description": "",
  "main": "./build/Release/test.node",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "install": "node-gyp rebuild"
  },
  "author": "",
  "license": "ISC",
  "gypfile": true
}
 

我們主要看和插件相關的兩個配置

"main": "./build/Release/test.node",
"gypfile": true
 

main定義了插件的入口,因為我們沒有為用戶提供js的api。而是直接提供.node文件,所以這里定義的路徑為插件的路徑。gypfile標記這個包是一個c++插件,用戶在使用npm安裝這個包的時候,就會執(zhí)行node-gyp rebuild,針對用戶系統(tǒng)環(huán)境,生成對應的二進制代碼。有些文章介紹了需要在scripts的值里加入"install": "node-gyp rebuild",npm文檔說了如果包下面有.gyp文件的話,默認就會執(zhí)行這個rebuild操作。

"scripts":{"install": "node-gyp rebuild"}
If there is a binding.gyp file in the root of your package and you have not defined an install or preinstall script, npm will default the install command to compile using node-gyp.

一切準備就緒,我們可以執(zhí)行npm publish發(fā)布了(記得先登錄npm)。 

測試

我們首先安裝這個包。npm install test-addons --unsafe-perm,然后寫代碼測試一下。

var addon = require("test-addons/build/Release/test");
console.log(addon.hello());                        
 

我們發(fā)現(xiàn),這樣顯然很麻煩。所以我們最好還是在包里為用戶提供js模塊的接口。我們在包里增加index.js

var addon = require("./build/Release/test");
module.exports = addon;                    
 

修改測試代碼

var addon = require("test-addons");
console.log(addon.hello());

到此,關于“怎么編寫nodejs c++插件”的學習就結束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續(xù)學習更多相關知識,請繼續(xù)關注億速云網(wǎng)站,小編會繼續(xù)努力為大家?guī)砀鄬嵱玫奈恼拢?/p>

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI