标签:style io ar sp for on 文件 数据 log
node-webkit客户端中应用本地数据库如果大量写入很多数据会导致主线程负责页面渲染和监听事件变慢。正如node介绍的那样,像这种CPU运算密集型操作,最好放到子进程中来处理。注意的是主进程和子进程的通讯与回调方法的执行。主进程与子进程是通过socket通讯,因些传递的参数只能是PlanObject型(json型),不能把回调函数什么的传过去。
主进程代码:mian.js
//子进程路径
var childpath=require(‘path‘).join(__dirname,"../childprocess/childprocess.js");
//生成子进程
var childprocess=require(‘child_process‘).fork(childpath);
//子进程运行事件监听
childprocess.on("error",function(err,stdout,stderr){
console.error("childprocess ERROR:",err,stdout,stderr);
})
// 异步回调
function Receipt(){
this.m={};
}
Receipt.prototype={
push:function(id,method){
this.m[id]=method;
},
invoke:function(id,args,scope){
if(!this.m[id])return;
this.m[id].apply(scope,args);
delete this.m[id];
},
remove:function(id){
if(this.m[id])
delete this.m[id];
}
}
//执行完消息的回调
var receipt = new Receipt();
/* 定义收到消息格式
{
id:"sendedId",
method:"childprocess method to call",
err:"null or error"
result:"sucess result"
}
*/
//收到消息监听
childprocess.on("message",function(msg){
console.log("主进程收到消息",msg);
if(msg&&msg.id){
receipt.invoke(msg.id,msg);
}
});
/* 定义发送消息格式
{
method:childprocess.method,
args:childprocess.method.arguments
id:thisCalledUniqueId
}
*/
var getMyMothod={method:"myMethod",args:[{"anyPlanetObj":"anyPlanetObj"},"two arg"],id:require(‘node-uuid‘)()};
receipt.push(getMyMothod.id,function(msg){
console.log("getMyMehtod callback called",msg);
});
childprocess.send(getMyMothod);
子进程代码:/childprocess/childprocess.js
var childprocess={
test:function(feedbackid){
if(process.send)process.send({id:feedbackid,method:"test",err:null,result:"test feedback ok"})
},
myMethod:function(sessoinObj,currentStr,feedbackid){
try{
/*your logic here*/
if(process.send) process.send({id:feedbackid,method:arguments.callee.name,err:null,result:"your result data"});
}cathe(e){
if(process.send) process.send({id:feedbackid,method:arguments.callee.name,err:e,result:null});
}
}
}
/*传入message消息的格式
{method:childprocess.method,
args:childprocess.method.arguments
id:thisCalledUnqueId}
*/
process.on("message",function(data){
if(data&&data.method){
data.args.push(data.id);
childprocess[data.method].apply(childprocess,data.args)
}else{
console.log("子进程","childprocess‘s message event no method!")
}
})
exports = module.exports = childprocess;
另外,如果是sqlite3在子进程中执行,在子进程中会缺少引用,子进程执行是在node内核中执行,它找的node_sqlite3.node目录就不一样,在sqlite3的包中的binding中创建文件夹为“node-v14-win32-ia32”再把node_sqlite3.node从别"node-webkit-v0.10.3-win32-ia32"等版本目录中考过去就可以正确执行了。
标签:style io ar sp for on 文件 数据 log
原文地址:http://my.oschina.net/u/265765/blog/353143