Guest User

Untitled

a guest
May 25th, 2018
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.04 KB | None | 0 0
  1. const mineType = {
  2. 'css': 'text/css',
  3. 'js': 'text/javascript',
  4. 'txt': 'text/plain',
  5. 'html': 'text/html',
  6. 'gif': 'image/gif',
  7. 'png': 'image/png',
  8. 'jpeg': 'image/jpeg',
  9. 'bmp': 'image/bmp',
  10. 'webp': 'image/webp'
  11. }
  12.  
  13. const makeStaticServer = function (req, res, rootPath) {
  14. const path = require('path')
  15. const url = require('url')
  16. const fs = require('fs')
  17.  
  18. const { pathname } = url.parse(req.url)
  19. const realPath = path.join(rootPath, '/static', pathname)
  20. const rs = fs.createReadStream(realPath)
  21. let chunkArr = []
  22. let len = 0
  23. rs.on('data', (chunk) => {
  24. chunkArr.push(chunk)
  25. len += chunk.length
  26. })
  27. rs.on('end', () => {
  28. let resultBuffer = Buffer.concat(chunkArr, len)
  29. res.statusCode = 200
  30. res.setHeader('Content-Type', mineType[pathname.slice(pathname.lastIndexOf('.') + 1)])
  31. res.setHeader('Content-Length', resultBuffer.length)
  32. res.setHeader('Cache-Control', 'max-age=120')
  33. res.end(resultBuffer)
  34. })
  35. rs.on('error', err => {
  36. console.log(err)
  37. })
  38. }
  39.  
  40. exports.makeStaticServer = makeStaticServer
Add Comment
Please, Sign In to add comment