1
0
Fork 0
mirror of https://github.com/seejohnrun/haste-server.git synced 2024-11-01 03:21:21 +00:00

preparse static elements rather than fs'ing them

This commit is contained in:
John Crepezzi 2011-11-18 17:36:35 -05:00
parent 0fe0306caa
commit b173cdd144
2 changed files with 18 additions and 18 deletions

View file

@ -8,6 +8,12 @@ var winston = require('winston');
var StaticHandler = function(path) { var StaticHandler = function(path) {
this.basePath = path; this.basePath = path;
this.defaultPath = '/index.html'; this.defaultPath = '/index.html';
// Grab the list of available files - and move into hash for quick lookup
var available = fs.readdirSync(this.basePath);
this.availablePaths = {};
for (var i = 0; i < available.length; i++) {
this.availablePaths['/' + available[i]] = true;
}
}; };
// Determine the content type for a given extension // Determine the content type for a given extension
@ -24,28 +30,23 @@ StaticHandler.contentTypeFor = function(ext) {
// Handle a request, and serve back the asset if it exists // Handle a request, and serve back the asset if it exists
StaticHandler.prototype.handle = function(incPath, response) { StaticHandler.prototype.handle = function(incPath, response) {
// Go to index if not found or /
if (!this.availablePaths[incPath]) incPath = this.defaultPath;
var filePath = this.basePath + (incPath == '/' ? this.defaultPath : incPath); var filePath = this.basePath + (incPath == '/' ? this.defaultPath : incPath);
// And then stream the file back
var _this = this; var _this = this;
path.exists(filePath, function(exists) { fs.readFile(filePath, function(error, content) {
if (exists) { if (error) {
fs.readFile(filePath, function(error, content) { winston.error('unable to read file', { path: filePath, error: error.message });
if (error) { response.writeHead(500, { 'content-type': 'application/json' });
winston.error('unable to read file', { path: filePath, error: error.message }); response.end(JSON.stringify({ message: 'IO: Unable to read file' }));
response.writeHead(500, { 'content-type': 'application/json' });
response.end(JSON.stringify({ message: 'IO: Unable to read file' }));
}
else {
var contentType = StaticHandler.contentTypeFor(path.extname(filePath));
response.writeHead(200, { 'content-type': contentType });
response.end(content, 'utf-8');
}
});
} }
else { else {
// serve the default route so that pushstate can work if not found var contentType = StaticHandler.contentTypeFor(path.extname(filePath));
_this.handle('/', response); response.writeHead(200, { 'content-type': contentType });
response.end(content, 'utf-8');
} }
}); });
}; };
module.exports = StaticHandler; module.exports = StaticHandler;

View file

@ -26,7 +26,6 @@ if (config.logging) {
} }
} }
// TODO preparse static instead of using exists
// TODO implement command line // TODO implement command line
// Set the server up // Set the server up