为Node.js编写组件的几种方式
简介
首先介绍使用v8 API跟使用swig框架的不同:
(1)v8 API方式为官方提供的原生方法,功能强大而完善,缺点是需要熟悉v8 API,编写起来比较麻烦,是js强相关的,不容易支持其它脚本语言。
(2)swig为第三方支持,一个强大的组件开发工具,支持为python、lua、js等多种常见脚本语言生成C++组件包装代码,swig使用者只需要编写C++代码和swig配置文件即可开发各种脚本语言的C++组件,不需要了解各种脚本语言的组件开发框架,缺点是不支持javascript的回调,文档和demo代码不完善,使用者不多。
二、纯JS实现Node.js组件
module.exports.Hello = function(name) {
console.log('Hello ' + name);
}
var m = require('helloworld');
m.Hello('zhangsan');
//输出: Hello zhangsan
三、 使用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
(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
var m = require('hello');
console.log(m.foo());
四、 使用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
*/
五、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);
}
六、其它
在使用v8 API实现Node.js组件时,可以发现跟实现Lua组件的相似之处,Lua有状态机,Node有Isolate。
Node实现对象导出时,需要实现一个构造函数,并为它增加“成员函数”,最后把构造函数导出为类名。Lua实现对象导出时,也需要实现一个创建对象的工厂函数,也需要把“成员函数”们加到table中。最后把工厂函数导出。
参考资料:
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

浙公网安备 33010602011771号