Node.jsのコンポーネントを記述するいくつかの方法

20799 ワード

本文は主にNode.js記述コンポーネントの3つの実装を忘れた:純js実装、v 8 API実装(同期&非同期)、swigフレームワークによる実装.
キーワード:Node.js、C++、v 8、swig、非同期、コールバック.
概要
まず、v 8 APIの使用とswigフレームワークの使用の違いについて説明します.
(1)v 8 API方式は公式に提供されるオリジナルの方法であり、機能が強く、完備している.欠点はv 8 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.
三、v 8 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.
四、v 8 APIを使用してJSコンポーネントを実現する——非同期モード
上記3のdemoは同期コンポーネントを記述し、foo()は同期関数、すなわちfoo()関数の呼び出し者はfoo()関数の実行が完了するのを待つ必要があり、foo()関数がIO消費時間操作のある関数である場合、非同期foo()関数はブロック待ちを低減し、全体の性能を向上させることができる.
非同期コンポーネントの実装はlibuvのuv_に注目するだけです.queue_work API、コンポーネント実装時、マスターコードhello.cppとコンポーネントコンシューマコードを除いて、他の部分は上の3つの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)
}

非同期の構想はとても簡単で、1つの仕事の関数、1つの完成の関数、1つのデータを載せてスレッドにまたがって伝送する構造体を実現して、uv_を呼び出しますqueue_ワークでいいです.難点はv 8データ構造、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)swigのパッケージcppファイルを生成するための*.iの作成
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;
   %template(vectorstr) vector;
};
上の%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は、通常、C++関数がvectorをパラメータまたは戻り値として使用し、jsコードを記述する際に使用する必要があるJSとして定義されたタイプのvectoriを表す.
swigがサポートするstlタイプの詳細については、次を参照してください.https://github.com/swig/swig/tree/master/Lib/javascript/v8
(3)node-gypコンパイル用binding.gypの作成
(4)warpper cppファイルの生成 生成時注意v 8バージョン情報、eg:swig -javascript -node -c++ -DV8_VERSION=0x040599 example.i
(5)コンパイル&テスト
難点はstlタイプ、カスタムタイプの使用で、公式ドキュメントが少なすぎることです.
swig-javascript対std::vector、std::string、のパッケージ使用参照:私の練習、
主に*.iファイルの実装に注目します.
六、その他
v 8 APIを用いてNode.jsコンポーネントを実装する場合,Luaコンポーネントを実装するのと類似点が見出され,Luaにはステートマシンがあり,NodeにはIsolateがある.
ノードがオブジェクトのエクスポートを実装する場合は、コンストラクション関数を実装して「メンバー関数」を追加し、最後にコンストラクション関数をクラス名にエクスポートする必要があります.Luaがオブジェクトのエクスポートを実装する場合は、オブジェクトを作成するファクトリ関数も実装し、tableに「メンバー関数」を追加する必要があります.最後にファクトリ関数をエクスポートします.
Nodeのjsスクリプトにはnewキーワードがあり、Luaにはないので、Luaは外部にオブジェクトファクトリのみを提供し、Nodeはオブジェクトファクトリまたはクラスパッケージを提供することができます.
付:Lua知識覚書.
この文書は次のとおりです.http://www.cnblogs.com/cswuyg/p/5215161.html 
 
参考資料:
1、v 8 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