server.js 1.1 KB

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