CCCPaste

Servidor en Node Js

index.js
var server = require ("./server");
var router = require ("./routers");
var requestHandlers = require ("./requestHandlers");

var handle ={}
handle ["/"] = requestHandlers.raiz;
handle ["/iniciar"] = requestHandlers.iniciar;
handle ["/busca"] = requestHandlers.busca;
handle ["/subir"] = requestHandlers.subir;

server.inicio (router.route,handle);


****************************************************************************************

server.js

var http=require ("http");
var url =require ("url");

function inicio (route,handle){
	function onRequest (request, response){
		var pathname =url.parse(request.url).pathname;
		console.log("Peticion para "+pathname+ " recibida.");

		route (handle,pathname,response);
	}
	http.createServer(onRequest).listen (8888);
	console.log ("Server Running");
}

exports.inicio=inicio;

****************************************************************************************

routers.js
function route (handle,pathname,response){

	console.log ("Rutear peticion a "+pathname );

	if (typeof handle[pathname] === 'function'){
		//return handle  [pathname]();
                  handle  [pathname](response);

	} else{
		console.log ("No hay manipulador para "+pathname);
		response.writeHead (404,{"Content-Type":"text/html"});
		response.write("404 no encontado");
		response.end()
		//return "404 no encontrado";
	}

}
exports.route =route;


****************************************************************************************


requestHandlers.js

var exec =require ("child_process").exec;

function raiz(response){
	console.log ("Manip. raiz / ");
	html (response,"raiz");
	//return "raiz /";
}

function iniciar (response){
	console.log ("Manip. iniciar ");

	exec ("ls -lah", function (error, stdout,stderr) {
		html (response,stdout);
	});	;
}

function busca (response){
	console.log ("Manip.busca");
	exec ("find /",
	{timeout:10000,maxBuffer:20000*1024},
	function (error,stdout, stderr){
		html(response,stdout);		
	});
}

function subir (response){
	console.log ("Manip. subir ");
	html (response,"sube");
	//return "Hola subir";
}

//Funciones auxiliares
function html(response,msg){
	response.writeHead ( 200 , {"Content-Type": "text/html"});
	response.write (msg);
	response.end();
}

exports.raiz=raiz;
exports.iniciar =iniciar;
exports.busca=busca;
exports.subir =subir;