Advertisement
Guest User

Untitled

a guest
Oct 21st, 2019
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.03 KB | None | 0 0
  1. var http = require('http');
  2. var pug = require('pug');
  3. var fs = require('fs');
  4. var myDB = 'alunos.json';
  5. var jsonfile = require('jsonfile');
  6. var {parse} = require('querystring');
  7.  
  8. var myserver = http.createServer(function(req,res){
  9. console.log(req.method + ' - ' + req.url);
  10. if(req.method == 'GET'){
  11. if(req.url== '/w3.css'){
  12. fs.readFile("w3.css",(erro, dados) =>{
  13. if(!erro){
  14. res.writeHead(200,{'Content-type':'text/css'})
  15. res.write(dados);
  16. }
  17. else{
  18. res.writeHead(200,{'Content-type':'text/plain'})
  19. res.write(pug.renderFile("Erro na leitura w3.css"));
  20. }
  21. res.end();
  22. })
  23. }
  24. else if(req.url=='/'){
  25. res.writeHead(200, {'Content-type': 'text/html; charset-utf-8'});
  26. res.write(pug.renderFile('index.pug'));
  27. res.end();
  28. }
  29. else if(req.url == '/alunos'){
  30. fs.readFile(myDB,(erro,dados)=>{
  31. if(!erro){
  32. res.writeHead(200,{'Content-type':'text/html'})
  33. res.write(pug.renderFile("lista-alunos.pug",{lista: JSON.parse(dados)}));
  34. res.end();
  35. }
  36. else{
  37. res.writeHead(200,{'Content-type': 'text/plain'});
  38. res.end("Erro " + erro);
  39. }
  40. });
  41.  
  42.  
  43. }
  44. else if(req.url == '/registar'){
  45. res.writeHead(200,{'Content-type':'text/html'})
  46. res.write(pug.renderFile("form-aluno.pug"));
  47. res.end()
  48. }
  49. else{
  50. res.end("Erro: Pedido não suportado {" + req.url + "}");
  51. }
  52. }
  53. else if(req.method == 'POST'){
  54. if(req.url == '/alunos'){
  55. recuperaInfo(req, resultado => {
  56. jsonfile.readFile(myDB, (erro, alunos) => {
  57. if(!erro){
  58. alunos.push(resultado);
  59. console.dir(alunos);
  60. jsonfile.writeFile(myDB,alunos,erro => {
  61. if(erro) console.log(erro);
  62. else console.log('Registo completo');
  63. })
  64. }
  65. })
  66. res.end(pug.renderFile('aluno-recebido.pug',{aluno: JSON.stringify(resultado)}))
  67. })
  68. }
  69. else{
  70. res.end("Erro pedido nao suportado {" + req.method + "}");
  71. }
  72. }
  73.  
  74.  
  75. });
  76.  
  77. myserver.listen(3021)
  78.  
  79.  
  80. function recuperaInfo(request, callback){
  81. if(request.headers['content-type'] == 'application/x-www-form-urlencoded'){
  82. let body = '';
  83. request.on('data', bloco => {
  84. body += bloco.toString();
  85. })
  86. request.on('end',() =>{
  87. callback(parse(body));
  88. })
  89. }
  90. else callback(null);
  91. }
  92.  
  93. console.log("Servidor a escuta na porta 3021");
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement