Skip to content

Instantly share code, notes, and snippets.

@puterjam
Created October 28, 2013 08:42
Show Gist options
  • Save puterjam/7193340 to your computer and use it in GitHub Desktop.
Save puterjam/7193340 to your computer and use it in GitHub Desktop.
简易的nodejs httpserver
(function(){
var http = require("http");
var fs = require('fs');
//默认启动http服务的路径
var documentRoot = process.cwd();
//默认文档名称
var defaultDocument = "index.htm";
var contentType = {
"*" : "application/octet-stream",
".ico" : "image/x-icon",
".jpe" : "image/jpeg",
".jpeg" : "image/jpeg",
".jpg" : "image/jpeg",
".png" : "image/png",
".html" : "text/html",
".htm" : "text/html",
".css" : "text/css",
".txt" : "text/plain",
".js" : "application/x-javascript"
}
var server = http.createServer(function(req,res){
var URI = ((/\/$/.test(req.url))?(req.url + defaultDocument):req.url).split("?");
var filename = documentRoot + URI[0];
var queryString = URI[1] || "";
var ext = (filename.match("\\.\\w+") || "*").toString().toLowerCase();
fs.exists(filename, function(exists){
if (exists) {
fs.readFile(filename, function(err, data){
if (err) {
res.writeHead(500, {'Content-Type' : "text/html"});
res.end("<h1>500</h1>");
throw err;
}
//写头部信息
res.writeHead(200, {'Content-Type' : contentType[ext] || "text/plain"});
res.end(data);
})
}else{
res.writeHead(404, {'Content-Type' : "text/html"});
res.end("<h1>404</h1>");
}
});
});
server.listen(8080,"127.0.0.1");
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment