server.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. var http = require('http'),
  2. url = require('url'),
  3. join = require('path').join,
  4. exists = require('path').exists,
  5. extname = require('path').extname,
  6. join = require('path').join,
  7. fs = require('fs'),
  8. port = process.argv[2] || 3000
  9. var mime = {
  10. 'html': 'text/html',
  11. 'css': 'text/css',
  12. 'js': 'application/javascript',
  13. }
  14. http.createServer(function(req, res){
  15. console.log(' \033[90m%s \033[36m%s\033[m', req.method, req.url)
  16. var pathname = url.parse(req.url).pathname,
  17. path = join(process.cwd(), pathname)
  18. function notFound() {
  19. res.statusCode = 404
  20. res.end("404 Not Found\n")
  21. }
  22. function error(err) {
  23. res.statusCode = 500
  24. res.end(err.message + "\n")
  25. }
  26. exists(path, function(exists){
  27. if (!exists) return notFound()
  28. fs.stat(path, function(err, stat){
  29. if (err) return error()
  30. if (stat.isDirectory()) path = join(path, 'index.html')
  31. res.setHeader('Cache-Control', 'no-cache')
  32. res.setHeader('Content-Type', mime[path.split('.').slice(-1)] || 'application/octet-stream')
  33. fs.createReadStream(path).pipe(res)
  34. })
  35. })
  36. }).listen(port)
  37. console.log('\n Server listening on %d\n', port)