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 jsonfile = require('jsonfile')
- var {parse} = require('querystring')
- var myBD = 'alunos.json'
- 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('Erro na leitura do 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(myBD, (erro, dados) => {
- if(!erro){
- res.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'})
- res.write(pug.renderFile('lista-alunos.pug',
- {lista: JSON.parse(dados)}))
- res.end()
- }
- else{
- res.writeHead(200, {'Content-Type': 'text/plain; charset=utf-8'})
- res.end('Erro: ' + erro)
- }
- })
- }
- else if(req.url == '/registar'){
- res.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'})
- 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(myBD, (erro, alunos)=>{
- if(!erro){
- alunos.push(resultado)
- // console.dir(alunos)
- jsonfile.writeFile(myBD, alunos, erro => {
- if(erro) console.log(erro)
- else console.log('Registo gravado com sucesso.')
- })
- }
- })
- res.end(pug.renderFile('aluno-recebido.pug', {aluno: JSON.stringify(resultado)}))
- })
- }
- else{
- res.end('Erro: pedido não suportado [' + req.url + ']')
- }
- }
- else{
- res.end('Erro: método não suportado [' + req.method + ']')
- }
- })
- myserver.listen(3021)
- console.log('Servidor à escuta na porta 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)
- }
Advertisement
Add Comment
Please, Sign In to add comment