-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstaticHandler.js
executable file
·40 lines (37 loc) · 1.16 KB
/
staticHandler.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/**
* @author Supal Dubey
* http://roadtobe.com/supaldubey/
**/
var path = require('path'),
fs = require('fs');
function handleStatic(pageUrl, response)
{
console.log("Empiezo a leer "+pageUrl);
//se crea la ruta absoluta del fichero
var filename = path.join(process.cwd()+'/static/', pageUrl);
//mira a ver si existe el fichero en esa ruta
fs.exists(filename, function(exists) {
if(!exists) {
console.log("No existe: " + filename);
response.writeHead(200, {'Content-Type': 'text/html'});
var error = path.join(process.cwd()+'/static/', "404.html");
var fileStream = fs.createReadStream(error);
fileStream.on('end', function() {
response.end();
});
fileStream.pipe(response);
return;
}
//Do not send Content type, browser will pick it up.
response.writeHead(200);
console.log("Empiezo a leer "+pageUrl);
var fileStream = fs.createReadStream(filename);
fileStream.on('end', function() {
response.end();
});
//envia fragmentos hasta acabar, cuando entonces llama al anterior on.('end') a ejecutar.
fileStream.pipe(response);
return;
});
}
exports.handleStatic = handleStatic;