Home > Article > Web Front-end > Three ways to implement components in Node.js_node.js
First introduce the difference between using v8 API and using swig framework:
(1) The v8 API method is the native method provided by the official, with powerful and complete functions. The disadvantage is that you need to be familiar with the v8 API, which is more troublesome to write. It is strongly related to js and cannot easily support other scripting languages.
(2) swig is a third-party support, a powerful component development tool that supports generating C++ component packaging code for a variety of common scripting languages such as python, lua, js, etc. swig users only need to write C++ code and swig configuration files You can develop C++ components in various scripting languages without knowing the component development frameworks of various scripting languages. The disadvantage is that it does not support JavaScript callbacks, the documentation and demo code are incomplete, and there are not many users.
1. Pure JS to implement Node.js components
(1) Go to the helloworld directory and execute npm init to initialize package.json. Ignore the various options and leave them as defaults.
(2) Component implementation index.js, for example:
module.exports.Hello = function(name) { console.log('Hello ' + name); }
(3) Execute in the outer directory: npm install ./helloworld, helloworld is then installed in the node_modules directory.
(4) Write component usage code:
var m = require('helloworld'); m.Hello('zhangsan'); //输出: Hello zhangsan
2. Use v8 API to implement JS components - synchronous mode
(1) Write binding.gyp, eg:
{ "targets": [ { "target_name": "hello", "sources": [ "hello.cpp" ] } ] }
(2) Write the implementation of the component 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) Compile component
node-gyp configure node-gyp build ./build/Release/目录下会生成hello.node模块。
(4) Write test js code
const m = require('./build/Release/hello') console.log(m.foo()); //输出 Hello World
(5) Add package.json for installation eg:
{ "name": "hello", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "node test.js" }, "author": "", "license": "ISC" }
(5) Install components to node_modules
Go to the superior directory of the component directory and execute: npm install ./helloc //Note: helloc is the component directory
The hello module will be installed in the node_modules directory in the current directory. The test code is written like this:
var m = require('hello'); console.log(m.foo());
3. Use v8 API to implement JS components - asynchronous mode
The above description is a synchronous component. foo() is a synchronous function, that is, the caller of the foo() function needs to wait for the foo() function to finish executing before proceeding. When the foo() function is an IO time-consuming operation, function, the asynchronous foo() function can reduce blocking waits and improve overall performance.
To implement asynchronous components, you only need to pay attention to the uv_queue_work API of libuv. When implementing the component, except for the main code hello.cpp and the component user code, other parts are consistent with the above three demos.
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) }
The idea of asynchronous is very simple. To implement a work function, a completion function, and a structure that carries data for cross-thread transmission, just call uv_queue_work. The difficulty is familiarity with v8 data structure and 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 implements Node.js components
Use swig framework to write Node.js components
(1) Write the implementation of the component: *.h and *.cpp
eg:
namespace a { class A{ public: int add(int a, int y); }; int add(int x, int y); }
(2) Write *.i, used to generate swig packaging cpp file
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>; };
The %apply above means that int* result, int* xx, std::string* result, std::string* yy, std::string& result in the code are output descriptions. This is a typemap, which is a replacement. .
If the pointer parameters in the C++ function parameters return a value (specified through OUTPUT in the *.i file), Swig will process them as the return value of the JS function. If there are multiple pointers, the return value of the JS function is list.
%template(vectori) vectorbd43222e33876353aff11e13a7dc75f6 means that a type vectori is defined for JS. This is usually a C++ function that uses vectorbd43222e33876353aff11e13a7dc75f6 as a parameter or return value. You need to use it when writing js code.
(3) Write binding.gyp for compilation using node-gyp
(4) Generate warpper cpp file. Pay attention to the v8 version information when generating, eg: swig -javascript -node -c++ -DV8_VERSION=0x040599 example.i
(5) Compile & test
The difficulty lies in the use of stl types and custom types. There are too few official documents in this regard.
swig - JavaScript encapsulation use of std::vector, std::string, see: My exercise, mainly focusing on the implementation of *.i files.
5. Others
When using v8 API to implement Node.js components, you can find similarities with implementing Lua components. Lua has a state machine and Node has Isolate.
When Node implements object export, it needs to implement a constructor, add a "member function" to it, and finally export the constructor as a class name. When Lua implements object export, it also needs to implement a factory function to create objects, and also needs to add "member functions" to the table. Finally, export the factory function.
Node’s js script has the new keyword, but Lua does not, so Lua only provides external object factories for creating objects, while Node can provide object factories or class encapsulation.
The above is the entire content of this article, I hope it will be helpful to everyone’s study.