87,992
社区成员
发帖
与我相关
我的任务
分享
Napi::Value Echo(const Napi::CallbackInfo &info)
{
if (info.Length() != 8)
{
Napi::TypeError::New(info.Env(), "参数不足").ThrowAsJavaScriptException();
return Napi::Boolean::New(info.Env(), false);
}
std::string strCom = info[0].As<Napi::String>();
int nBaundRate = info[1].As<Napi::Number>().Int32Value();
std::string strParity = info[2].As<Napi::String>();
unsigned char nDataSize = info[3].As<Napi::Number>().Int32Value();
std::string strStopBits = info[4].As<Napi::String>();
Napi::Function okcb = info[5].As<Napi::Function>();
Napi::Function errcb = info[6].As<Napi::Function>();
Napi::Function progresscb = info[7].As<Napi::Function>();
CZLCom *zlcom = new CZLCom(okcb, errcb, progresscb);
zlcom->Queue();
if (zlcom->Open(strCom, nBaundRate, strParity, nDataSize, strStopBits))
{
/* code */
return Napi::Boolean::New(info.Env(), false);
}
else
{
return Napi::Boolean::New(info.Env(), true);
}
}
。。。。。。
Napi::Object CZLComWrapper::Init(Napi::Env env, Napi::Object exports)
{
Napi::Function func = DefineClass(
env, "ZLComWrapper",
{InstanceMethod("open", &CZLComWrapper::Open),
InstanceMethod("close", &CZLComWrapper::Close),
InstanceMethod("getValue", &CZLComWrapper::GetValue),
StaticMethod<&CZLComWrapper::CreateNewItem>("CreateNewItem")});
Napi::FunctionReference *constructor = new Napi::FunctionReference();
*constructor = Napi::Persistent(func);
env.SetInstanceData(constructor);
exports.Set("ZLComWrapper", func);
return exports;
}
。。。。。。
Napi::Value CZLComWrapper::Open(const Napi::CallbackInfo &info)
{
if (info.Length() != 8)
{
Napi::TypeError::New(info.Env(), "参数不足").ThrowAsJavaScriptException();
return Napi::Boolean::New(info.Env(), false);
}
std::string strCom = info[0].As<Napi::String>();
int nBaundRate = info[1].As<Napi::Number>().Int32Value();
std::string strParity = info[2].As<Napi::String>();
unsigned char nDataSize = info[3].As<Napi::Number>().Int32Value();
std::string strStopBits = info[4].As<Napi::String>();
Napi::Function okcb = info[5].As<Napi::Function>();
Napi::Function errcb = info[6].As<Napi::Function>();
Napi::Function progresscb = info[7].As<Napi::Function>();
m_pCom = new CZLCom(okcb, errcb, progresscb);
m_pCom->Queue();
if (m_pCom->Open(strCom, nBaundRate, strParity, nDataSize, strStopBits))
{
return info.Env().Undefined();
}
return Napi::Boolean::New(info.Env(), false);
}
。。。。。。
Napi::Object Init(Napi::Env env, Napi::Object exports)
{
exports.Set(
Napi::String::New(env, "echo"),
Napi::Function::New(env, Echo));
return CZLComWrapper::Init(env, exports);
}
const addon = require('./build/Debug/greet.node')
const onOk = (msg) => {
console.log(msg);
};
const onErr = (msg) => {
console.log(msg);
};
const onProgress = (msg) => {
console.log(msg);
};
// 类方式
var com = new addon.ZLComWrapper();
var ret = com.open("com3", 9600, "n", 8, "1", onOk, onErr, onProgress);
console.log(ret);
// 函数方式
// var ret = addon.echo("com3", 9600, "n", 8, "1", onOk, onErr, onProgress);
// console.log(ret);