Advertisement
Guest User

Static-files Handler

a guest
May 20th, 2017
180
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const url = require('url')
  2. const fs = require('fs')
  3. const path = require('path')
  4.  
  5. function getContentType (url) {
  6.   if (url.endsWith('css')) {
  7.     return 'text/css'
  8.   }
  9.   if (url.endsWith('ico')){
  10.     return 'image/x-icon'
  11.   }
  12. }
  13.  
  14. module.exports = (req, res) => {
  15.   req.pathname = req.pathname || url.parse(req.url).pathname
  16.  
  17.   if (req.pathname.startsWith('/content/') && req.method === 'GET') {
  18.     let filePath = path.normalize(
  19.       path.join(__dirname, `..${req.pathname}`))
  20.  
  21.     fs.readFile(filePath, (err, data) => {
  22.       if (err) {
  23.         res.writeHead(404, {
  24.           'Content-Type': 'text/plain'
  25.         })
  26.  
  27.         res.write('Resource not found!')
  28.         res.end()
  29.         return
  30.       }
  31.  
  32.       res.writeHead(200, {
  33.         'Content-Type': getContentType(req.pathname) //checks for file's content type
  34.       })
  35.  
  36.       // Sending data and ending response
  37.       res.write(data)
  38.       res.end()
  39.     })
  40.   } else {
  41.     return true
  42.   }
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement