nodejs中c++和js交换二进制数据,采用 buffer。同时以下列子展示了v8常用到的一些其他类型转换技巧.
项目中
#include <zlib.h> 是zlib库,在linux下编译时候注意带上 -lz参数,比如vi ./build/***.target.mk 修改这个文件,找到
LIBS :=
然后修改为
LIBS := -lz 即可编译运行。
binary-v8-buffer.rar 可参考用例。
-
#include <string.h>
-
#include <string>
-
#include <v8.h>
-
#include <node.h>
-
#include <node_buffer.h>
-
#include <zlib.h> //zlib库
-
using namespace node;
-
using namespace v8;
-
using namespace std;
-
-
Handle<Value> lz_uncompress(const Arguments& args) {
-
HandleScope scope;
-
if(args.Length() < 1) {
-
ThrowException(Exception::TypeError(String::New("Wrong number of arguments")));
-
return scope.Close(Undefined());
-
}
-
-
//String, Number, Boolean, Object, Array等对象都是从Value继承而来,
-
//所以很好判断类型,通过 "Is系列函数",如 IsNumber
-
//另外通过“To系列函数”,如ToNumber
-
//
-
Local<Value> arg1 = args[0];
-
if (Buffer::HasInstance(arg1)) {
-
size_t size = Buffer::Length(arg1->ToObject());
-
char* bufferdata = Buffer::Data(arg1->ToObject());
-
-
unsigned char buf [1024] = {'\0'};
-
uLong bufLen = sizeof(buf);
-
int ret = uncompress(buf, &bufLen, (const Bytef*)(bufferdata), (uLong)size);
-
if(ret != Z_OK){
-
ThrowException(Exception::TypeError(String::New("destination memory too little")));
-
return scope.Close(Undefined());
-
}
-
return scope.Close(String::New((const char*)buf,bufLen));
-
}
-
else{
-
ThrowException(Exception::TypeError(String::New("input is not Buffer data")));
-
return scope.Close(Undefined());
-
}
-
-
}
-
-
// Convert a JavaScript string to a std::string.
-
// To not bother too much with string encodings
-
//we just use ascii.
-
string ObjectToString(Local<Value> value) {
-
String::Utf8Value utf8_value(value);
-
return string(*utf8_value);
-
}
-
-
Handle<Value> lz_compress(const Arguments& args) {
-
HandleScope scope;
-
if(args.Length() < 1) {
-
ThrowException(Exception::TypeError(String::New("Wrong number of arguments")));
-
return scope.Close(Undefined());
-
}
-
-
-
//v8::String::Utf8Value param1(args[0]->ToString());
-
//std::string rawStr = std::string(*param1);
-
Local<Value> arg1 = args[0];
-
std::string rawStr = ObjectToString(arg1);
-
-
unsigned char buf [1024] = {'\0'};
-
uLong bufLen = sizeof(buf);
-
int ret = compress(buf, &bufLen, (const Bytef*)(rawStr.c_str()), (uLong)rawStr.length());
-
if(ret != Z_OK){
-
ThrowException(Exception::TypeError(String::New("destination memory too little")));
-
return scope.Close(Undefined());
-
}
-
-
Buffer *outBuf = Buffer::New ((const char*)buf, bufLen);
-
return scope.Close(outBuf->handle_);
-
}
-
-
-
void init(Handle<Object> target) {
-
-
NODE_SET_METHOD(target, "compress", lz_compress);
-
NODE_SET_METHOD(target, "uncompress", lz_uncompress);
-
}
-
-
NODE_MODULE(LZzlib, init);
阅读(9462) | 评论(0) | 转发(0) |