Advertisement
xapu

Untitled

Oct 9th, 2017
613
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const viewAllPath = './views/viewAll.html'
  2. const addMemePath = './views/addMeme.html'
  3. const getDetailsPath = './views/details.html'
  4. const dbPath = './db/db.json'
  5. const fs = require('fs')
  6. const url = require('url')
  7. const util = require('util')
  8. const randomstring = require('randomstring')
  9. const formidable = require('formidable')
  10. // count of img-s per folder
  11. const maxFilesInFolder = 10
  12.  
  13. function viewAll (req, res) {
  14.   fs.readFile(viewAllPath, 'utf8', (err, data) => {
  15.     if (err) {
  16.       console.log(err)
  17.       return
  18.     }
  19.     res.writeHead(200, {
  20.       'Content-Type': 'text/html'
  21.     })
  22.     fs.readFile(dbPath, 'utf8', (err, db) => {
  23.       if (err) {
  24.         console.log(err)
  25.         return
  26.       }
  27.       db = JSON.parse(db)
  28.       db = db.sort((a, b) => {
  29.         return parseInt(b.dateStamp) - parseInt(a.dateStamp)
  30.       })
  31.       let memes = []
  32.       for (let index in db) {
  33.         let meme = db[index]
  34.         // if (meme.privacy === 'on') {
  35.         memes.push(
  36.           `<div class="meme">
  37.                         <a href="/getDetails?id=${meme.id}">
  38.                         <img class="memePoster" height="150" src="${meme.memeSrc}"/>          
  39.                       </div>`
  40.         )
  41.         // }
  42.       }
  43.  
  44.       data = data.replace(
  45.         '<div id="replaceMe">{{replaceMe}}</div>',
  46.         memes.join('')
  47.       )
  48.       res.end(data)
  49.     })
  50.   })
  51. }
  52.  
  53. function viewAddMeme (req, res) {
  54.   fs.readFile(addMemePath, 'utf8', (err, data) => {
  55.     if (err) {
  56.       console.log(err)
  57.       return
  58.     }
  59.     res.writeHead(200, {
  60.       'Content-Type': 'text/html'
  61.     })
  62.     res.end(data)
  63.   })
  64. }
  65.  
  66. // not finished
  67. function addMeme (req, res) {
  68.   let form = new formidable.IncomingForm()
  69.  
  70.   // opens the core storage folder
  71.   fs.readdir('./public/memeStorage/', (err, foldersData) => {
  72.  
  73.     // there is no point to loop over all folders
  74.  
  75.     // this will check the count of elems in the folder and try to access the folder with name with length-1
  76.     // so if there is 1 elem named 0 it will access the 0 folder
  77.     // !!! you must always have folder named 0, even if you have 0 elems
  78.  
  79.     let folderLength = foldersData.length - 1
  80.  
  81.     // first we will read the folder that is named with highest number
  82.     fs.readdir(`./public/memeStorage/${folderLength}`, (err, data) => {
  83.       if (err) {
  84.         console.log(err)
  85.         return
  86.       }
  87.  
  88.       // this will check if the folder is overfiled
  89.       // and if it is it will increment the folderLenght variable
  90.       if (data.length >= maxFilesInFolder) {
  91.         folderLength++
  92.       }
  93.  
  94.       let folderName = `./public/memeStorage/${folderLength.toString()}`
  95.  
  96.       // this will check if the folder you are looking for exists and if not will create a new one with sync function
  97.       if (foldersData.indexOf(folderLength.toString()) === -1) {
  98.         fs.mkdirSync(folderName)
  99.       }
  100.  
  101.       // set the folder path to the form
  102.  
  103.       form.uploadDir = folderName
  104.  
  105.       form.parse(req, function (err, fields, files) {
  106.         res.writeHead(200, {
  107.           'content-type': 'text/plain'
  108.         })
  109.  
  110.         // an atempt reads the original db file
  111.         fs.readFile(dbPath, 'utf8', (err, data) => {
  112.           if (err) {
  113.             console.log(err)
  114.             return
  115.           }
  116.  
  117.           // gets the existing db as JSON
  118.           data = JSON.parse(data)
  119.  
  120.           // creates a new item for the db
  121.           let entry = {
  122.             id: randomstring.generate(10),
  123.             memeSrc: files.meme.path,
  124.             memeTitle: fields.memeTitle,
  125.             status: fields.status,
  126.             memeDescription: fields.memeDescription,
  127.             dateStamp: Date.now()
  128.           }
  129.  
  130.           // add the new entry to the db
  131.           data.push(entry)
  132.  
  133.           // creates a new file for the db(wtih the newest entry)
  134.           fs.writeFile('./db/db1.json', JSON.stringify(data), err => {
  135.             if (err) {
  136.               console.log(err)
  137.               return
  138.             }
  139.             console.log(`The file has been saved in folder ${folderName}`)
  140.           })
  141.           res.write('received upload:\n\n')
  142.           res.end(
  143.             util.inspect({
  144.               fields: fields,
  145.               files: files
  146.             })
  147.           )
  148.         })
  149.       })
  150.     })
  151.   })
  152. }
  153.  
  154. function getDetails (req, res) {
  155.   fs.readFile(getDetailsPath, 'utf8', (err, data) => {
  156.     if (err) {
  157.       console.log(err)
  158.       return
  159.     }
  160.     res.writeHead(200, {
  161.       'Content-Type': 'text/html'
  162.     })
  163.     fs.readFile(dbPath, 'utf8', (err, db) => {
  164.       if (err) {
  165.         console.log(err)
  166.         return
  167.       }
  168.       let memeId = url.parse(req.url, true).query.id
  169.       db = JSON.parse(db)
  170.       for (let targetedMeme of db) {
  171.         if (targetedMeme.id === memeId) {
  172.           let memeHtml = `<div class="content">
  173.       <img src="${targetedMeme.memeSrc}" alt=""/>
  174.       <h3>Title  ${targetedMeme.title}</h3>
  175.       <p> ${targetedMeme.description}</p>
  176.       <button><a href="${targetedMeme.memeSrc}" download>Download Meme</a></button>
  177.       </div>`
  178.  
  179.           data = data.replace(
  180.             '<div id="replaceMe">{{replaceMe}}</div>',
  181.             memeHtml
  182.           )
  183.           res.end(data)
  184.         }
  185.       }
  186.     })
  187.   })
  188. }
  189.  
  190. module.exports = (req, res) => {
  191.   if (req.pathname === '/viewAllMemes' && req.method === 'GET') {
  192.     viewAll(req, res)
  193.   } else if (req.pathname === '/addMeme' && req.method === 'GET') {
  194.     viewAddMeme(req, res)
  195.   } else if (req.pathname === '/addMeme' && req.method === 'POST') {
  196.     addMeme(req, res)
  197.   } else if (req.pathname.startsWith('/getDetails') && req.method === 'GET') {
  198.     getDetails(req, res)
  199.   } else {
  200.     return true
  201.   }
  202. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement