var http = require('http') var fs = require('fs') var template = require('art-template') var url = require('url')
var comments = [ { name: '张三', message: '今天天气不错!', dateTime: '2015-10-16' }, { name: '张三2', message: '今天天气不错!', dateTime: '2015-10-16' }, { name: '张三3', message: '今天天气不错!', dateTime: '2015-10-16' }, { name: '张三4', message: '今天天气不错!', dateTime: '2015-10-16' }, { name: '张三5', message: '今天天气不错!', dateTime: '2015-10-16' } ]
http .createServer(function(req, res){ var parseObj = url.parse(req.url, true) var pathName = parseObj.pathname if(pathName === '/'){ fs.readFile('./views/index.html', function (err, data) { if(!err){ var htmlStr = template.render(data.toString(), { comments: comments }) res.end(htmlStr) } else return res.end('404 Not Found.') }) } else if(pathName === '/pinglun'){
var comment = parseObj.query comment.dateTime = '2015-10-22' comments.push(comment)
res.statusCode = 302 res.setHeader('location', '/') res.end() } else if(pathName === '/post'){ fs.readFile('./views/post.html', function(err, data){ if(!err){ res.end(data) } else return res.end('4040 Not Found.') }) } else if(pathName.indexOf('/public/') === 0){ fs.readFile('.' + pathName, function(err, data){ if(!err){ res.end(data) } else return res.end('404 Not Found.') }) } else fs.readFile('./views/404.html',function(err, data){ if(!err) return res.end(data) else return res.end('404 Not Found') })
}) .listen(3000,function(){ console.log('server running...') })
|