Node.js编写组件的三种实现方式
首先介绍使用v8API跟使用swig框架的不同:
(1)v8API方式为官方提供的原生方法,功能强大而完善,缺点是需要熟悉v8API,编写起来比较麻烦,是js强相关的,不容易支持其它脚本语言。
(2)swig为第三方支持,一个强大的组件开发工具,支持为python、lua、js等多种常见脚本语言生成C++组件包装代码,swig使用者只需要编写C++代码和swig配置文件即可开发各种脚本语言的C++组件,不需要了解各种脚本语言的组件开发框架,缺点是不支持javascript的回调,文档和demo代码不完善,使用者不多。
一、纯JS实现Node.js组件
(1)到helloworld目录下执行npminit初始化package.json,各种选项先不管,默认即可。
(2)组件的实现index.js,例如:
module.exports.Hello=function(name){
console.log('Hello'+name);
}
(3)在外层目录执行:npminstall./helloworld,helloworld于是安装到了node_modules目录中。
(4)编写组件使用代码:
varm=require('helloworld');
m.Hello('zhangsan');
//输出:Hellozhangsan
二、使用v8API实现JS组件——同步模式
(1)编写binding.gyp,eg:
{
"targets":[
{
"target_name":"hello",
"sources":["hello.cpp"]
}
]
}
(2)编写组件的实现hello.cpp,eg:
#include<node.h>
namespacecpphello{
usingv8::FunctionCallbackInfo;
usingv8::Isolate;
usingv8::Local;
usingv8::Object;
usingv8::String;
usingv8::Value;
voidFoo(constFunctionCallbackInfo<Value>&args){
Isolate*isolate=args.GetIsolate();
args.GetReturnValue().Set(String::NewFromUtf8(isolate,"HelloWorld"));
}
voidInit(Local<Object>exports){
NODE_SET_METHOD(exports,"foo",Foo);
}
NODE_MODULE(cpphello,Init)
}
(3)编译组件
node-gypconfigure node-gypbuild ./build/Release/目录下会生成hello.node模块。
(4)编写测试js代码
constm=require('./build/Release/hello')
console.log(m.foo());//输出HelloWorld
(5)增加package.json用于安装eg:
{
"name":"hello",
"version":"1.0.0",
"description":"",
"main":"index.js",
"scripts":{
"test":"nodetest.js"
},
"author":"",
"license":"ISC"
}
(5)安装组件到node_modules
进入到组件目录的上级目录,执行:npminstall./helloc//注:helloc为组件目录
会在当前目录下的node_modules目录下安装hello模块,测试代码这样子写:
varm=require('hello');
console.log(m.foo());
三、使用v8API实现JS组件——异步模式
上面描述的是同步组件,foo()是一个同步函数,也就是foo()函数的调用者需要等待foo()函数执行完才能往下走,当foo()函数是一个有IO耗时操作的函数时,异步的foo()函数可以减少阻塞等待,提高整体性能。
异步组件的实现只需要关注libuv的uv_queue_workAPI,组件实现时,除了主体代码hello.cpp和组件使用者代码,其它部分都与上面三的demo一致。
hello.cpp:
/*
*Node.jscppAddonsdemo:asynccallandcallback.
*gcc4.8.2
*author:cswuyg
*Date:2016.02.22
**/
#include<iostream>
#include<node.h>
#include<uv.h>
#include<sstream>
#include<unistd.h>
#include<pthread.h>
namespacecpphello{
usingv8::FunctionCallbackInfo;
usingv8::Function;
usingv8::Isolate;
usingv8::Local;
usingv8::Object;
usingv8::Value;
usingv8::Exception;
usingv8::Persistent;
usingv8::HandleScope;
usingv8::Integer;
usingv8::String;
//asynctask
structMyTask{
uv_work_twork;
inta{0};
intb{0};
intoutput{0};
unsignedlonglongwork_tid{0};
unsignedlonglongmain_tid{0};
Persistent<Function>callback;
};
//asyncfunction
voidquery_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);//1second
}
//asynccompletecallback
voidquery_finish(uv_work_t*work,intstatus){
Isolate*isolate=Isolate::GetCurrent();
HandleScopehandle_scope(isolate);
MyTask*task=(MyTask*)work->data;
constunsignedintargc=3;
std::stringstreamstream;
stream<<task->main_tid;
std::stringmain_tid_s{stream.str()};
stream.str("");
stream<<task->work_tid;
std::stringwork_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();
deletetask;
}
//asyncmain
voidasync_foo(constFunctionCallbackInfo<Value>&args){
Isolate*isolate=args.GetIsolate();
HandleScopehandle_scope(isolate);
if(args.Length()!=3){
isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate,"argumentsnum:3")));
return;
}
if(!args[0]->IsNumber()||!args[1]->IsNumber()||!args[2]->IsFunction()){
isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate,"argumentserror")));
return;
}
MyTask*my_task=newMyTask;
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);
}
voidInit(Local<Object>exports){
NODE_SET_METHOD(exports,"foo",async_foo);
}
NODE_MODULE(cpphello,Init)
}
异步的思路很简单,实现一个工作函数、一个完成函数、一个承载数据跨线程传输的结构体,调用uv_queue_work即可。难点是对v8数据结构、API的熟悉。
test.js
//testhelloUVmodule
'usestrict';
constm=require('helloUV')
m.foo(1,2,(a,b,c)=>{
console.log('finishjob:'+a);
console.log('mainthread:'+b);
console.log('workthread:'+c);
});
/*
output:
finishjob:3
mainthread:139660941432640
workthread:139660876334848
*/
四、swig-javascript实现Node.js组件
利用swig框架编写Node.js组件
(1)编写好组件的实现:*.h和*.cpp
eg:
namespacea{
classA{
public:
intadd(inta,inty);
};
intadd(intx,inty);
}
(2)编写*.i,用于生成swig的包装cpp文件
eg:
/*File:IExport.i*/
%modulemy_mod
%include"typemaps.i"
%include"std_string.i"
%include"std_vector.i"
%{
#include"export.h"
%}
%applyint*OUTPUT{int*result,int*xx};
%applystd::string*OUTPUT{std::string*result,std::string*yy};
%applystd::string&OUTPUT{std::string&result};
%include"export.h"
namespacestd{
%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++函数参数中的指针参数,如果是返回值的(通过*.i文件中的OUTPUT指定),swig都会把他们处理为JS函数的返回值,如果有多个指针,则JS函数的返回值是list。
%template(vectori)vector<int>则表示为JS定义了一个类型vectori,这一般是C++函数用到vector<int>作为参数或者返回值,在编写js代码时,需要用到它。
(3)编写binding.gyp,用于使用node-gyp编译
(4)生成warppercpp文件生成时注意v8版本信息,eg:swig-javascript-node-c++-DV8_VERSION=0x040599example.i
(5)编译&测试
难点在于stl类型、自定义类型的使用,这方面官方文档太少。
swig-javascript对std::vector、std::string、的封装使用参见:我的练习,主要关注*.i文件的实现。
五、其它
在使用v8API实现Node.js组件时,可以发现跟实现Lua组件的相似之处,Lua有状态机,Node有Isolate。
Node实现对象导出时,需要实现一个构造函数,并为它增加“成员函数”,最后把构造函数导出为类名。Lua实现对象导出时,也需要实现一个创建对象的工厂函数,也需要把“成员函数”们加到table中。最后把工厂函数导出。
Node的js脚本有new关键字,Lua没有,所以Lua对外只提供对象工厂用于创建对象,而Node可以提供对象工厂或者类封装。
以上就是本文的全部内容,希望对大家的学习有所帮助。