初学nodejs,为了理解他的运行机制,写了下面的代码,想了解一下它对http请求的处理机制 var express = require('express'); var http = require('http'); var path = require('path'); var events = require('events'); var emitter = new events.EventEmitter(); var sleep = require('sleep');
var app = express();
// all environments app.set('port', process.env.PORT || 3000); app.set('views', __dirname + '/views'); app.set('view engine', 'ejs'); app.use(express.favicon()); app.use(express.logger('dev')); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(express.cookieParser('your secret here')); app.use(express.session()); app.use(app.router); app.use(express.static(path.join(__dirname, 'public')));
// development only if ('development' == app.get('env')) { app.use(express.errorHandler()); }
//app.get('/', routes.index); //app.get('/users', user.list); function SynFun(){ this.count = 0; } SynFun.prototype.syncount = function(){ var self = this; emitter.emit('syncount',self);
}
SynFun.prototype.asyncount = function(){ var self = this; emitter.emit('asyncount',self); }
emitter.on('syncount',function(obj){ console.log("======== ____syncount begin,time:" + new Date().getTime() ); obj.count = obj.count + 1; sleep.sleep(20); console.log("======== ____syncount end,time:" + new Date().getTime() ); });
emitter.on('asyncount',function(obj){ console.log("======== ____asyncount begin,time:" + new Date().getTime() ); obj.count = obj.count + 1; console.log("======== ____asyncount end,time:" + new Date().getTime() ); });
var synFun = new SynFun();
app.get('/syncount',function(req,res){ console.log("========syncount requset begin,time:" + new Date().getTime() ); console.log("====== syncount begin count:" + synFun.count); synFun.syncount(); console.log("====== syncount end count:" + synFun.count); console.log("========syncount request end,time:" + new Date().getTime()); });
app.get('/asyncount',function(req,res){ console.log("========asyncount requset begin,time:" + new Date().getTime()); console.log("====== asyncount begin count:" + synFun.count); synFun.asyncount(); console.log("====== asyncount end count:" + synFun.count); console.log("========asyncount request end,time:" + new Date().getTime()); });
http.createServer(app).listen(app.get('port'), function(){ console.log('Express server listening on port ' + app.get('port')); });
上面的代码,我先请求运行syncount,之后休眠20妙,再运行asyncount,发现asyncount请求被阻塞了,似乎http的请求是串行执行的,如果这样哪性能岂不堪忧?但网上牛人的测试数据看似乎不存在这个问题,请有经验的朋友指教,谢谢!