const app = require('express')(); const server = require('http').Server(app);
http.createServer的用法
var http=require("http");
http.createServer(function(req,res){
res.writeHead(200,{
"content-type":"text/plain"
});
res.write("hello nodejs");
res.end();
}).listen(3000);
源码解读
app = require('express')(); //infact, app is a requestListener function.
var http = require('http').Server(app); // infact, function Server eqs http.createServer;
var proto = require('./application');
exports = module.exports = createApplication;
function createApplication() {
var app = function(req, res, next) {
app.handle(req, res, next);
};
mixin(app, EventEmitter.prototype, false);
mixin(app, proto, false);
app.request = { __proto__: req, app: app };
app.response = { __proto__: res, app: app };
app.init();
return app;
}
app.listen = function listen() {
var server = http.createServer(this);
return server.listen.apply(server, arguments);
};
function Server(requestListener) {
if (!(this instanceof Server)) return new Server(requestListener);
net.Server.call(this, { allowHalfOpen: true });
if (requestListener) {
this.addListener('request', requestListener);
}
this.httpAllowHalfOpen = false;
this.addListener('connection', connectionListener);
this.addListener('clientError', function(err, conn) {
conn.destroy(err);
});