為Node.js編寫組件的幾種方式


本文主要備忘為Node.js編寫組件的三種實現:純js實現、v8 API實現(同步&異步)、借助swig框架實現。

關鍵字:Node.js、C++、v8、swig、異步、回調。

簡介

首先介紹使用v8 API跟使用swig框架的不同:

(1)v8 API方式為官方提供的原生方法,功能強大而完善,缺點是需要熟悉v8 API,編寫起來比較麻煩,是js強相關的,不容易支持其它腳本語言。

(2)swig為第三方支持,一個強大的組件開發工具,支持為python、lua、js等多種常見腳本語言生成C++組件包裝代碼,swig使用者只需要編寫C++代碼和swig配置文件即可開發各種腳本語言的C++組件,不需要了解各種腳本語言的組件開發框架,缺點是不支持javascript的回調,文檔和demo代碼不完善,使用者不多。

二、純JS實現Node.js組件

(1)到helloworld目錄下執行npm init 初始化package.json,各種選項先不管,默認即可,更多package.json信息參見:https://docs.npmjs.com/files/package.json。
(2)組件的實現index.js,例如:
module.exports.Hello = function(name) {
        console.log('Hello ' + name);
}
(3)在外層目錄執行:npm install ./helloworld,helloworld於是安裝到了node_modules目錄中。
(4)編寫組件使用代碼:
var m = require('helloworld');
m.Hello('zhangsan');
//輸出: Hello zhangsan

完整demo

三、 使用v8 API實現JS組件——同步模式

 (1)編寫binding.gyp, eg:

{
  "targets": [
    {
      "target_name": "hello",
      "sources": [ "hello.cpp" ]
    }
  ]
}

關於binding.gyp的更多信息參見:https://github.com/nodejs/node-gyp

(2)編寫組件的實現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/目錄下會生成hello.node模塊。

 (4)編寫測試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

進入到組件目錄的上級目錄,執行:npm install ./helloc //注:helloc為組件目錄
會在當前目錄下的node_modules目錄下安裝hello模塊,測試代碼這樣子寫:
var m = require('hello');
console.log(m.foo());   

完整demo

四、 使用v8 API實現JS組件——異步模式

上面三的demo描述的是同步組件,foo()是一個同步函數,也就是foo()函數的調用者需要等待foo()函數執行完才能往下走,當foo()函數是一個有IO耗時操作的函數時,異步的foo()函數可以減少阻塞等待,提高整體性能。

異步組件的實現只需要關注libuv的uv_queue_work API,組件實現時,除了主體代碼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)
}

異步的思路很簡單,實現一個工作函數、一個完成函數、一個承載數據跨線程傳輸的結構體,調用uv_queue_work即可。難點是對v8 數據結構、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
*/

完整demo

五、swig-javascript 實現Node.js組件

利用swig框架編寫Node.js組件

(1)編寫好組件的實現:*.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++導出函數返回值一般定義為void,函數參數中的指針參數,如果是返回值的(通過*.i文件中的OUTPUT指定),swig都會把他們處理為JS函數的返回值,如果有多個指針,則JS函數的返回值是list。
%template(vectori) vector<int> 則表示為JS定義了一個類型vectori,這一般是C++函數用到vector<int> 作為參數或者返回值,在編寫js代碼時,需要用到它。
swig支持的更多的stl類型參見:https://github.com/swig/swig/tree/master/Lib/javascript/v8
(3)編寫binding.gyp,用於使用node-gyp編譯
(4)生成warpper cpp文件 生成時注意v8版本信息,eg:swig -javascript -node -c++ -DV8_VERSION=0x040599 example.i
(5)編譯&測試
難點在於stl類型、自定義類型的使用,這方面官方文檔太少。
swig - javascript對std::vector、std::string、的封裝使用參見: 我的練習主要關注*.i文件的實現

六、其它

在使用v8 API實現Node.js組件時,可以發現跟實現Lua組件的相似之處,Lua有狀態機,Node有Isolate。

Node實現對象導出時,需要實現一個構造函數,並為它增加“成員函數”,最后把構造函數導出為類名。Lua實現對象導出時,也需要實現一個創建對象的工廠函數,也需要把“成員函數”們加到table中。最后把工廠函數導出。

Node的js腳本有new關鍵字,Lua沒有,所以Lua對外只提供對象工廠用於創建對象,而Node可以提供對象工廠或者類封裝。
附: Lua知識備忘錄

本文所在:http://www.cnblogs.com/cswuyg/p/5215161.html 

 

參考資料:

1、v8 API參考文檔:https://v8docs.nodesource.com/node-5.0/index.html

2、swig-javascript文檔:http://www.swig.org/Doc3.0/Javascript.html

3、C++開發Node.js組件:https://nodejs.org/dist/latest-v4.x/docs/api/addons.html#addons_addons

4、swig-javascript demo:https://github.com/swig/swig/tree/master/Examples/javascript/simple

5、C++開發Node.js組件 demo:https://github.com/nodejs/node-addon-examples


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM