I would like to know how I could improve this code. Thus, it would avoid too many excesses - initial errors. Moreover, through these modifications I could understand, understand, learn in another way. This would add new features and gain more performance.
Then this is the code
File path.js in folder js /
var fs = require('fs'),
url = require('url'),
path = require('path'),
http = require('http');
var caminho = {};
caminho['/'] = root;
caminho['/1'] = adminuser;
caminho['/2'] = userguest;
caminho['/3'] = usertemp;
caminho['/4'] = usersign;
caminho['/5'] = useranon;
function root(response){
response.writeHead(200, {'Content-type': 'text/html'});
response.write('<h1>Usuário Principal.</h1>');
response.end(); }
function adminuser(response){
response.writeHead(200, {'Content-type': 'text/html'});
response.write('<h1>Usuário Administrativo.</h1>');
response.end();}
function userguest(response){
response.writeHead(200, {'Content-type': 'text/html'});
response.write('<h1>Usuário Convidado.</h1>');
response.end(); }
function usertemp(response){
response.writeHead(200, {'Content-type': 'text/html'});
response.write('<h1>Usuário Temporário.</h1>');
response.end();}
function usersign(response){
response.writeHead(200, {'Content-type': 'text/html'});
response.write('<h1>Usuário Inscrito.</h1>');
response.end();}
function useranon(response){
response.writeHead(200, {'Content-type': 'text/html'});
response.write('<h1>Usuário Não Inscrito, Usuário Anónimo.</h1>');
response.end();}
module.exports.caminho = caminho;
File route.js in folder js /
function rota(caminho, url, response){
if(typeof caminho[url] === 'function'){
return caminho[url](response);
}else{
response.writeHead(404, {'Content-type': 'text/html'});
response.write('<h1>Página não encontrada.</h1>');
response.end();
}
}
module.exports.rota = rota;
Index.js file outside the folder inside the desktop
var http = require('http'),
rota = require('./js/rota.js'),
caminho = require('./js/caminho.js'),
aqui = require('url'),
path = require("path"),
fs = require("fs");
http.createServer(function(request, response){
url = aqui.parse(request.url).pathname;
console.log(url);
rota.rota(caminho.caminho, url, response);
}).listen(8080, 'localhost', function(){
console.log("\n localhost \n\n ctrl+c to exit");
});
node > node index.js
Result you access localhost and have routes. How can we improve the code? Would it be nice to use switch, case? Ps: If you can how can I add html files inside the routes with fs readfile?