jcramalho

DAW2019::Servidor::galunos2

Oct 22nd, 2019
273
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var http = require('http')
  2. var pug = require('pug')
  3. var fs = require('fs')
  4. var jsonfile = require('jsonfile')
  5.  
  6. var {parse} = require('querystring')
  7.  
  8. var myBD = "alunos.json"
  9.  
  10. var myServer = http.createServer((req,res)=>{
  11.  
  12.     console.log(req.method + ' ' + req.url)
  13.  
  14.     if(req.method == 'GET'){
  15.         if((req.url == '/')||(req.url == '/alunos')){
  16.             jsonfile.readFile(myBD, (erro, alunos) => {
  17.                 if(!erro){
  18.                     res.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'})
  19.                     res.write(pug.renderFile('index.pug', {lista: alunos}))
  20.                     res.end()
  21.                 }
  22.                 else{
  23.                     res.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'})
  24.                     res.write(pug.renderFile('erro.pug', {e: "Erro: na leitura da BD"}))
  25.                     res.end()
  26.                 }
  27.             })
  28.         }
  29.         else if(req.url == '/w3.css'){
  30.             res.writeHead(200, {'Content-Type': 'text/css'})
  31.             fs.readFile('w3.css', (erro, dados)=>{
  32.                 if(!erro) res.write(dados)
  33.                 else res.write(pug.renderFile('erro.pug', {e: erro}))
  34.                 res.end()
  35.             })
  36.         }
  37.         else if(req.url == '/apagar.js'){
  38.             res.writeHead(200, {'Content-Type': 'text/javascript'})
  39.             fs.readFile('apagar.js', (erro, dados)=>{
  40.                 if(!erro) res.write(dados)
  41.                 else res.write(pug.renderFile('erro.pug', {e: erro}))
  42.                 res.end()
  43.             })
  44.         }
  45.         else{
  46.             res.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'})
  47.             console.log("Erro: "+ req.url +" não está implementado!")
  48.             res.write(pug.renderFile('erro.pug', {e: "Erro: "+ req.url +" não está implementado!"}))
  49.             res.end()
  50.         }
  51.     }
  52.     else if(req.method == 'POST'){
  53.         if(req.url == '/'){
  54.             recuperaInfo(req, resultado => {
  55.                 jsonfile.readFile(myBD, (erro, alunos)=>{
  56.                     if(!erro){
  57.                         alunos.push(resultado)
  58.                         // console.dir(alunos)
  59.                         jsonfile.writeFile(myBD, alunos, erro => {
  60.                             if(erro) console.log(erro)
  61.                             else console.log('Registo gravado com sucesso.')
  62.                             res.end(pug.renderFile('index.pug', {lista: alunos}))
  63.                         })
  64.                     }
  65.                     else
  66.                     res.end(pug.renderFile('index.pug', {lista: alunos}))
  67.                 })
  68.             })
  69.         }
  70.         else{
  71.             res.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'})
  72.             console.log("Erro: "+ req.url +" não está implementado!")
  73.             res.write(pug.renderFile('erro.pug', {e: "Erro: "+ req.url +" não está implementado!"}))
  74.             res.end()
  75.         }
  76.     }
  77.     else if(req.method == 'DELETE'){
  78.         if(req.url.startsWith('/')){
  79.             var id = req.url.split('/')[1]
  80.             jsonfile.readFile(myBD, (erro, alunos)=>{
  81.                 if(!erro){
  82.                     var index = alunos.findIndex(a => a.identificador == id)
  83.                     if(index > -1){
  84.                         alunos.splice(index, 1)
  85.                         jsonfile.writeFile(myBD, alunos, erro => {
  86.                             if(erro) console.log(erro)
  87.                             else console.log('BD atualizada com sucesso.')
  88.                         })
  89.                         res.end('0')
  90.                     }
  91.                     else {
  92.                         console.log('Erro: não consegui encontrar o elemento a remover...')
  93.                         res.end('1')
  94.                     }
  95.                 }
  96.                 else{
  97.                     console.log('Erro na leitura da BD...')
  98.                     res.end('1')
  99.                 }
  100.             })
  101.         }
  102.     }
  103.     else{
  104.         res.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'})
  105.         console.log("Método: "+req.method+" não suportado!")
  106.         res.write(pug.renderFile('erro.pug', {e: "Método: "+req.method+" não suportado!"}))
  107.         res.end()
  108.     }
  109. })
  110.  
  111. myServer.listen(4006, ()=>{
  112.     console.log('Servidor à escuta na porta 4006...')
  113. })
  114.  
  115. function recuperaInfo(request, callback){
  116.     if(request.headers['content-type'] == 'application/x-www-form-urlencoded'){
  117.         let body = ''
  118.         request.on('data', bloco => {
  119.             body += bloco.toString()
  120.         })
  121.         request.on('end', ()=>{
  122.             callback(parse(body))
  123.         })
  124.     }
  125.     else callback(null)
  126. }
Advertisement
Add Comment
Please, Sign In to add comment