>  기사  >  웹 프론트엔드  >  Node.js_node.js에서 구성 요소를 구현하는 세 가지 방법

Node.js_node.js에서 구성 요소를 구현하는 세 가지 방법

WBOY
WBOY원래의
2016-05-16 15:13:441620검색

먼저 v8 API 사용과 swig 프레임워크 사용의 차이점을 소개합니다.

(1) v8 API 방식은 공식에서 제공하는 기본 방식으로 강력하고 완전한 기능을 갖추고 있으며, v8 API에 익숙해야 한다는 점은 작성하기가 더 까다롭다는 점입니다. js로 변경되었으며 다른 스크립팅 언어를 쉽게 지원할 수 없습니다.

(2) swig는 Python, Lua, js 등과 같은 다양한 일반 스크립팅 언어에 대한 C++ 구성 요소 패키징 코드 생성을 지원하는 강력한 구성 요소 개발 도구인 타사 지원입니다. swig 사용자는 다음 작업만 수행하면 됩니다. C++ 코드 및 swig 구성 파일 작성 다양한 스크립팅 언어의 컴포넌트 개발 프레임워크를 몰라도 다양한 스크립팅 언어로 C++ 컴포넌트를 개발할 수 있습니다. 단점은 JavaScript 콜백을 지원하지 않으며 문서 및 데모 코드가 불완전하다는 점입니다. 사용자가 많지 않습니다.

1. Node.js 구성 요소를 구현하는 순수 JS
(1) helloworld 디렉터리로 이동하여 npm init를 실행하여 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

2. v8 API를 사용하여 JS 구성요소 구현 - 동기 모드
(1) 바인딩.gyp를 작성합니다. 예:

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

(2) hello.cpp 구성 요소의 구현을 작성합니다. 예:

#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을 추가합니다. 예:

{                                                                                                         
  "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은 컴포넌트 디렉터리입니다
hello 모듈은 현재 디렉터리의 node_modules 디렉터리에 설치됩니다. 테스트 코드는 다음과 같이 작성됩니다.

var m = require('hello');
console.log(m.foo());  

3. v8 API를 사용하여 JS 구성요소 구현 - 비동기 모드
위의 설명은 동기식 구성 요소입니다. foo()는 동기식 함수입니다. 즉, foo() 함수의 호출자는 foo() 함수가 계속 진행되기 전에 실행이 완료될 때까지 기다려야 합니다. IO 시간이 많이 걸리는 작업, 함수, 비동기 foo() 함수는 차단 대기를 줄이고 전반적인 성능을 향상시킬 수 있습니다.

비동기 구성 요소를 구현하려면 libuv의 uv_queue_work API에만 주의하면 됩니다. 구성 요소를 구현할 때 기본 코드 hello.cpp 및 구성 요소 사용자 코드를 제외하고 다른 부분은 위의 세 가지 데모와 일치합니다.

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
*/

4. swig-javascript는 Node.js 구성 요소를 구현합니다
swig 프레임워크를 사용하여 Node.js 구성 요소 작성

(1) 구성요소 구현 작성: *.h 및 *.cpp

예:

namespace a {
  class A{
  public:
    int add(int a, int y);
  };
  int add(int x, int y);
}

(2) swig 패키징 cpp 파일을 생성하는 데 사용되는 *.i를 작성합니다
예:

/* 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가 출력 설명임을 의미합니다. 교체.
C++ 함수 매개변수의 포인터 매개변수가 값(*.i 파일의 OUTPUT을 통해 지정됨)을 반환하는 경우 Swig는 이를 JS 함수의 반환 값으로 처리합니다. 포인터가 여러 개인 경우 JS 함수의 반환 값입니다. 목록입니다.
%template(벡터i) 벡터는 JS에 대해 벡터i 유형이 정의됨을 의미합니다. 이는 일반적으로 js 코드를 작성할 때 벡터를 사용하는 C++ 함수입니다.
(3) node-gyp를 사용하여 컴파일을 위한 바인딩.gyp 작성
(4) 워퍼 cpp 파일을 생성할 때 v8 버전 정보에 주의하세요. 예: swig -javascript -node -c++ -DV8_VERSION=0x040599 example.i
(5) 컴파일 및 테스트
stl 유형과 사용자 정의 유형을 사용하는 데 어려움이 있습니다. 이와 관련된 공식 문서가 너무 적습니다.
swig - std::벡터, std::string의 JavaScript 캡슐화 사용, 참조: 내 연습, 주로 *.i 파일 구현에 중점을 둡니다.
5. 기타
v8 API를 사용하여 Node.js 구성 요소를 구현할 때 Lua 구성 요소에는 상태 머신이 있고 Node에는 Isolate가 있습니다.

Node가 객체 내보내기를 구현할 때 생성자를 구현하고 여기에 "멤버 함수"를 추가한 다음 마지막으로 생성자를 클래스 이름으로 내보내야 합니다. Lua가 객체 내보내기를 구현할 때 객체를 생성하기 위한 팩토리 함수도 구현해야 하며 테이블에 "멤버 함수"를 추가해야 합니다. 마지막으로 팩토리 함수를 내보냅니다.

Node의 js 스크립트에는 new 키워드가 있지만 Lua에는 없기 때문에 Lua는 객체 생성을 위한 외부 객체 팩토리만 제공하는 반면 Node는 객체 팩토리 또는 클래스 캡슐화를 제공할 수 있습니다.

위 내용은 이 글의 전체 내용입니다. 모든 분들의 공부에 도움이 되었으면 좋겠습니다.

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.