nodejs两个例子
1.nodejs多线程
var cluster=require("cluster");//ͨ¹ýcluster¿ÉÒÔ·Ö³öһЩ×ÓÏß³Ì
var http=require("http");
var numCPUs=require("os").cpus().length;//»ñµÃCPUÊǼ¸ºË
console.log(numCPUs);
var rssWarn=(12*1024*1024);
var heapWarn=(10 * 1024 * 1024);
if (cluster.isMaster) {
for (i = 0; i < numCPUs; i++) {
var worker = cluster.fork();
worker.on("message", function (m) {
if (m.memory) {
if (m.memory.rss > rssWarn) {
console.log('Worker' + m.process + " using to much memory");
}else {
console.log('Worker' + m.process + " is processing");
}
}
})
}
cluster.on("death", function (worker) {
console.log("worker " + worker.pid + ' died');
cluster.fork();
});
}else {
http.Server(function (req, res) {
res.writeHead(200);
res.end("Hello World\n");
}).listen(3000);
setInterval(function report() {
process.send({ "memory": process.memoryUsage(), "process": process.pid });
}, 1000);
}
2.nodejs日志分块
var fs=require('fs');
var log='D:/nodejs/log_file.log';//ÈÕÖ¾Îļþ·¾¶
var buf;
var childPath=__dirname;//·Ö¸îµÄÈÕÖ¾Îļþ´æ·ÅµÄ·¾¶
var buf_size=1024*10;//·Ö¸îÈÕÖ¾Îļþ×ÓÎļþ×î´óµÄ´óС
var logSize;//ÇóµÄÈÕÖ¾Îļþ´óС
var offse=0;
fs.stat(log,function(err,stats){
if(err) throw err;
logSize=stats.size;//µÃµ½Îļþ´óС
//´ò¿ªÎļþ
fs.open(log,'r',0666,function(err,fd){
if(err) throw err;
buf=new Buffer(buf_size);
readLog(fd);
});
});
var lognumber=0;
function readLog(fd){
lognumber++;
//¶ÁÈ¡ÈÕÖ¾
fs.read(fd,buf,0,buf_size,offse,function(err){
if(err) throw err;
logArr=buf.toString('utf8').split('\n');
var last=false;
if(offse+buf_size<logSize){
last=logArr.pop();
// console.log(last);
}
writeChildLog(childPath+"/logchild"+lognumber+'.log',logArr);
// console.log(offse+"|"+last.length+"|"+logSize);
if(last.length>0){
offse+=buf_size-last.length;
// console.log(offse);
buf=new Buffer(buf_size);
if(offse<logSize){
readLog(fd);
}
}
});
}
function writeChildLog(filename,logArr){
console.log(logArr.join("\n"));
fs.open(filename,'w',function(err,fd){
if(err) throw err;
fs.write(fd,logArr.join("\n"),0,'utf8',function(e){
if (e) throw e;
fs.close(fd);
});
});
}