Node.js編寫組件的三種實(shí)現(xiàn)方式
首先介紹使用v8 API跟使用swig框架的不同:
(1)v8 API方式為官方提供的原生方法,功能強(qiáng)大而完善,缺點(diǎn)是需要熟悉v8 API,編寫起來(lái)比較麻煩,是js強(qiáng)相關(guān)的,不容易支持其它腳本語(yǔ)言。
(2)swig為第三方支持,一個(gè)強(qiáng)大的組件開(kāi)發(fā)工具,支持為python、lua、js等多種常見(jiàn)腳本語(yǔ)言生成C++組件包裝代碼,swig使用者只需要編寫C++代碼和swig配置文件即可開(kāi)發(fā)各種腳本語(yǔ)言的C++組件,不需要了解各種腳本語(yǔ)言的組件開(kāi)發(fā)框架,缺點(diǎn)是不支持javascript的回調(diào),文檔和demo代碼不完善,使用者不多。
一、純JS實(shí)現(xiàn)Node.js組件
(1)到helloworld目錄下執(zhí)行npm init 初始化package.json,各種選項(xiàng)先不管,默認(rèn)即可。
(2)組件的實(shí)現(xiàn)index.js,例如:
module.exports.Hello = function(name) { console.log('Hello ' + name); }
(3)在外層目錄執(zhí)行:npm install ./helloworld,helloworld于是安裝到了node_modules目錄中。
(4)編寫組件使用代碼:
var m = require('helloworld'); m.Hello('zhangsan'); //輸出: Hello zhangsan
二、 使用v8 API實(shí)現(xiàn)JS組件——同步模式
(1)編寫binding.gyp, eg:
{ "targets": [ { "target_name": "hello", "sources": [ "hello.cpp" ] } ] }
(2)編寫組件的實(shí)現(xiàn)hello.cpp,eg:
#include <node.h> namespace cpphello { using v8::FunctionCallbackInfo; using v8::Isolate; using v8::Local; using v8::Object; using v8::String; using v8::Value; void Foo(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = args.GetIsolate(); args.GetReturnValue().Set(String::NewFromUtf8(isolate, "Hello World")); } void Init(Local<Object> exports) { NODE_SET_METHOD(exports, "foo", Foo); } NODE_MODULE(cpphello, Init) }
(3)編譯組件
node-gyp configure node-gyp build ./build/Release/目錄下會(huì)生成hello.node模塊。
(4)編寫測(cè)試js代碼
const m = require('./build/Release/hello') console.log(m.foo()); //輸出 Hello World
(5)增加package.json 用于安裝 eg:
{ "name": "hello", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "node test.js" }, "author": "", "license": "ISC" }
(5)安裝組件到node_modules
進(jìn)入到組件目錄的上級(jí)目錄,執(zhí)行:npm install ./helloc //注:helloc為組件目錄
會(huì)在當(dāng)前目錄下的node_modules目錄下安裝hello模塊,測(cè)試代碼這樣子寫:
var m = require('hello'); console.log(m.foo());
三、 使用v8 API實(shí)現(xiàn)JS組件——異步模式
上面描述的是同步組件,foo()是一個(gè)同步函數(shù),也就是foo()函數(shù)的調(diào)用者需要等待foo()函數(shù)執(zhí)行完才能往下走,當(dāng)foo()函數(shù)是一個(gè)有IO耗時(shí)操作的函數(shù)時(shí),異步的foo()函數(shù)可以減少阻塞等待,提高整體性能。
異步組件的實(shí)現(xiàn)只需要關(guān)注libuv的uv_queue_work API,組件實(shí)現(xiàn)時(shí),除了主體代碼hello.cpp和組件使用者代碼,其它部分都與上面三的demo一致。
hello.cpp:
/* * Node.js cpp Addons demo: async call and call back. * gcc 4.8.2 * author:cswuyg * Date:2016.02.22 * */ #include <iostream> #include <node.h> #include <uv.h> #include <sstream> #include <unistd.h> #include <pthread.h> namespace cpphello { using v8::FunctionCallbackInfo; using v8::Function; using v8::Isolate; using v8::Local; using v8::Object; using v8::Value; using v8::Exception; using v8::Persistent; using v8::HandleScope; using v8::Integer; using v8::String; // async task struct MyTask{ uv_work_t work; int a{0}; int b{0}; int output{0}; unsigned long long work_tid{0}; unsigned long long main_tid{0}; Persistent<Function> callback; }; // async function void query_async(uv_work_t* work) { MyTask* task = (MyTask*)work->data; task->output = task->a + task->b; task->work_tid = pthread_self(); usleep(1000 * 1000 * 1); // 1 second } // async complete callback void query_finish(uv_work_t* work, int status) { Isolate* isolate = Isolate::GetCurrent(); HandleScope handle_scope(isolate); MyTask* task = (MyTask*)work->data; const unsigned int argc = 3; std::stringstream stream; stream << task->main_tid; std::string main_tid_s{stream.str()}; stream.str(""); stream << task->work_tid; std::string work_tid_s{stream.str()}; Local<Value> argv[argc] = { Integer::New(isolate, task->output), String::NewFromUtf8(isolate, main_tid_s.c_str()), String::NewFromUtf8(isolate, work_tid_s.c_str()) }; Local<Function>::New(isolate, task->callback)->Call(isolate->GetCurrentContext()->Global(), argc, argv); task->callback.Reset(); delete task; } // async main void async_foo(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = args.GetIsolate(); HandleScope handle_scope(isolate); if (args.Length() != 3) { isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "arguments num : 3"))); return; } if (!args[0]->IsNumber() || !args[1]->IsNumber() || !args[2]->IsFunction()) { isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "arguments error"))); return; } MyTask* my_task = new MyTask; my_task->a = args[0]->ToInteger()->Value(); my_task->b = args[1]->ToInteger()->Value(); my_task->callback.Reset(isolate, Local<Function>::Cast(args[2])); my_task->work.data = my_task; my_task->main_tid = pthread_self(); uv_loop_t *loop = uv_default_loop(); uv_queue_work(loop, &my_task->work, query_async, query_finish); } void Init(Local<Object> exports) { NODE_SET_METHOD(exports, "foo", async_foo); } NODE_MODULE(cpphello, Init) }
異步的思路很簡(jiǎn)單,實(shí)現(xiàn)一個(gè)工作函數(shù)、一個(gè)完成函數(shù)、一個(gè)承載數(shù)據(jù)跨線程傳輸?shù)慕Y(jié)構(gòu)體,調(diào)用uv_queue_work即可。難點(diǎn)是對(duì)v8 數(shù)據(jù)結(jié)構(gòu)、API的熟悉。
test.js
// test helloUV module 'use strict'; const m = require('helloUV') m.foo(1, 2, (a, b, c)=>{ console.log('finish job:' + a); console.log('main thread:' + b); console.log('work thread:' + c); }); /* output: finish job:3 main thread:139660941432640 work thread:139660876334848 */
四、swig-javascript 實(shí)現(xiàn)Node.js組件
利用swig框架編寫Node.js組件
(1)編寫好組件的實(shí)現(xiàn):*.h和*.cpp
eg:
namespace a { class A{ public: int add(int a, int y); }; int add(int x, int y); }
(2)編寫*.i,用于生成swig的包裝cpp文件
eg:
/* File : IExport.i */ %module my_mod %include "typemaps.i" %include "std_string.i" %include "std_vector.i" %{ #include "export.h" %} %apply int *OUTPUT { int *result, int* xx}; %apply std::string *OUTPUT { std::string* result, std::string* yy }; %apply std::string &OUTPUT { std::string& result }; %include "export.h" namespace std { %template(vectori) vector<int>; %template(vectorstr) vector<std::string>; };
上面的%apply表示代碼中的 int* result、int* xx、std::string* result、std::string* yy、std::string& result是輸出描述,這是typemap,是一種替換。
C++函數(shù)參數(shù)中的指針參數(shù),如果是返回值的(通過(guò)*.i文件中的OUTPUT指定),swig都會(huì)把他們處理為JS函數(shù)的返回值,如果有多個(gè)指針,則JS函數(shù)的返回值是list。
%template(vectori) vector<int> 則表示為JS定義了一個(gè)類型vectori,這一般是C++函數(shù)用到vector<int> 作為參數(shù)或者返回值,在編寫js代碼時(shí),需要用到它。
(3)編寫binding.gyp,用于使用node-gyp編譯
(4)生成warpper cpp文件 生成時(shí)注意v8版本信息,eg:swig -javascript -node -c++ -DV8_VERSION=0x040599 example.i
(5)編譯&測(cè)試
難點(diǎn)在于stl類型、自定義類型的使用,這方面官方文檔太少。
swig - javascript對(duì)std::vector、std::string、的封裝使用參見(jiàn):我的練習(xí),主要關(guān)注*.i文件的實(shí)現(xiàn)。
五、其它
在使用v8 API實(shí)現(xiàn)Node.js組件時(shí),可以發(fā)現(xiàn)跟實(shí)現(xiàn)Lua組件的相似之處,Lua有狀態(tài)機(jī),Node有Isolate。
Node實(shí)現(xiàn)對(duì)象導(dǎo)出時(shí),需要實(shí)現(xiàn)一個(gè)構(gòu)造函數(shù),并為它增加“成員函數(shù)”,最后把構(gòu)造函數(shù)導(dǎo)出為類名。Lua實(shí)現(xiàn)對(duì)象導(dǎo)出時(shí),也需要實(shí)現(xiàn)一個(gè)創(chuàng)建對(duì)象的工廠函數(shù),也需要把“成員函數(shù)”們加到table中。最后把工廠函數(shù)導(dǎo)出。
Node的js腳本有new關(guān)鍵字,Lua沒(méi)有,所以Lua對(duì)外只提供對(duì)象工廠用于創(chuàng)建對(duì)象,而Node可以提供對(duì)象工廠或者類封裝。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助。
相關(guān)文章
npm安裝依賴報(bào)錯(cuò)ERESOLVE?unable?to?resolve?dependency?tree的解決方
當(dāng)我們拿到一個(gè)前端項(xiàng)目的時(shí)候,想要把它運(yùn)行起來(lái),首先是要給它安裝依賴,下面這篇文章主要給大家介紹了關(guān)于npm安裝依賴報(bào)錯(cuò)ERESOLVE?unable?to?resolve?dependency?tree的解決方法,需要的朋友可以參考下2023-04-04npm?install?XXX安裝路徑文件夾權(quán)限問(wèn)題的解決過(guò)程
這篇文章主要給大家介紹了關(guān)于npm?install?XXX安裝路徑文件夾權(quán)限問(wèn)題(npm?ERR!?The?operation?was?rejected?by?your?operating?system.errno?-4080)的解決過(guò)程,文中通過(guò)圖文介紹的非常詳細(xì),需要的朋友可以參考下2023-04-04Node.js使用SQLite數(shù)據(jù)庫(kù)方法大全
Node.js是一種流行的JavaScript運(yùn)行時(shí),提供了許多有用的模塊和庫(kù)來(lái)構(gòu)建Web應(yīng)用程序,而SQLite是一種嵌入式關(guān)系型數(shù)據(jù)庫(kù),它可以運(yùn)行在各種操作系統(tǒng)上,包括Windows、Linux和Mac OS X等,在Node.js中,可以通過(guò)安裝sqlite3模塊來(lái)訪問(wèn)SQLite數(shù)據(jù)庫(kù)2023-10-10Nodejs Express 通過(guò)log4js寫日志到Logstash(ELK)
這篇文章主要介紹了Nodejs Express 通過(guò)log4js寫日志到Logstash(ELK),小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-08-08node.js中express中間件body-parser的介紹與用法詳解
這篇文章主要給大家介紹了關(guān)于node.js中express中間件body-parser的相關(guān)資料,文章通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起看看吧。2017-05-05解決Window10系統(tǒng)下Node安裝報(bào)錯(cuò)的問(wèn)題分析
今天電腦重裝了win10系統(tǒng),在安裝Node的過(guò)程中出現(xiàn)了下面的問(wèn)題,下面就和大家分享下用來(lái)解決這種問(wèn)題的小方法2016-12-12Node.js?queryString?解析和格式化網(wǎng)址查詢字符串工具使用
這篇文章主要為大家介紹了Node.js?queryString?解析和格式化網(wǎng)址查詢字符串工具使用詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-04-04node.js中的fs.rmdirSync方法使用說(shuō)明
這篇文章主要介紹了node.js中的fs.rmdirSync方法使用說(shuō)明,本文介紹了fs.rmdirSync方法說(shuō)明、語(yǔ)法、接收參數(shù)、使用實(shí)例和實(shí)現(xiàn)源碼,需要的朋友可以參考下2014-12-12Node.js中JavaScript操作MySQL的常用方法整理
這篇文章主要介紹了Node.js中JavaScript操作MySQL的常用方法整理,包括作者對(duì)使用MySQL模塊連接池時(shí)錯(cuò)誤解決的一個(gè)記錄,需要的朋友可以參考下2016-03-03