Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var http = require('http');
- var pug = require('pug');
- var fs = require('fs');
- var myDB = 'alunos.json';
- var jsonfile = require('jsonfile');
- var {parse} = require('querystring');
- var myserver = http.createServer(function(req,res){
- console.log(req.method + ' - ' + req.url);
- if(req.method == 'GET'){
- if(req.url== '/w3.css'){
- fs.readFile("w3.css",(erro, dados) =>{
- if(!erro){
- res.writeHead(200,{'Content-type':'text/css'})
- res.write(dados);
- }
- else{
- res.writeHead(200,{'Content-type':'text/plain'})
- res.write(pug.renderFile("Erro na leitura w3.css"));
- }
- res.end();
- })
- }
- else if(req.url=='/'){
- res.writeHead(200, {'Content-type': 'text/html; charset-utf-8'});
- res.write(pug.renderFile('index.pug'));
- res.end();
- }
- else if(req.url == '/alunos'){
- fs.readFile(myDB,(erro,dados)=>{
- if(!erro){
- res.writeHead(200,{'Content-type':'text/html'})
- res.write(pug.renderFile("lista-alunos.pug",{lista: JSON.parse(dados)}));
- res.end();
- }
- else{
- res.writeHead(200,{'Content-type': 'text/plain'});
- res.end("Erro " + erro);
- }
- });
- }
- else if(req.url == '/registar'){
- res.writeHead(200,{'Content-type':'text/html'})
- res.write(pug.renderFile("form-aluno.pug"));
- res.end()
- }
- else{
- res.end("Erro: Pedido não suportado {" + req.url + "}");
- }
- }
- else if(req.method == 'POST'){
- if(req.url == '/alunos'){
- recuperaInfo(req, resultado => {
- jsonfile.readFile(myDB, (erro, alunos) => {
- if(!erro){
- alunos.push(resultado);
- console.dir(alunos);
- jsonfile.writeFile(myDB,alunos,erro => {
- if(erro) console.log(erro);
- else console.log('Registo completo');
- })
- }
- })
- res.end(pug.renderFile('aluno-recebido.pug',{aluno: JSON.stringify(resultado)}))
- })
- }
- else{
- res.end("Erro pedido nao suportado {" + req.method + "}");
- }
- }
- });
- myserver.listen(3021)
- function recuperaInfo(request, callback){
- if(request.headers['content-type'] == 'application/x-www-form-urlencoded'){
- let body = '';
- request.on('data', bloco => {
- body += bloco.toString();
- })
- request.on('end',() =>{
- callback(parse(body));
- })
- }
- else callback(null);
- }
- console.log("Servidor a escuta na porta 3021");
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement