Skip to content

Instantly share code, notes, and snippets.

@evandertino
Last active August 29, 2015 14:05
Show Gist options
  • Save evandertino/795702b671b31ea59a1c to your computer and use it in GitHub Desktop.
Save evandertino/795702b671b31ea59a1c to your computer and use it in GitHub Desktop.
A Simple NodeJS File Server with caching abilities
/*
* Before executing this script
*
* 1. Create a dir named content
* 2. With an index.html that requests for files e.g css
*
* This simple server will automatically fetch the
* requested resource from the content directory
*
* author: Evander Tino
*
*/
var http = require('http');
var fs = require('fs');
var path = require('path');
var mimeTypes = {
'.js' : 'text/javascript',
'.html': 'text/html',
'.css' : 'text/css'
};
var cache = {};
function cacheAndDeliver(f, cb) {
fs.stat(f, function (err, stats) {
if (err) {
return console.log('Oh no!, Error', err);
}
var lastChanged = Date.parse(stats.ctime),
isUpdated = (cache[f]) && lastChanged > cache[f].timestamp;
if (!cache[f] || isUpdated) {
fs.readFile(f, function(err, data) {
console.log('loading ' + f + ' from disk');
if (!err) {
cache[f] = {content: data, timestamp: Date.now()};
}
cb(err, data);
});
return;
}
console.log('loading ' + f + ' from cache');
cb(null, cache[f].content);
});
}
http.createServer(function (request, response) {
var lookup = path.basename(decodeURI(request.url)) || 'index.html';
var f = 'content/' + lookup;
fs.exists(f, function (exists) {
if (exists) {
cacheAndDeliver(f, function (err, data) {
if (err) {
response.writeHead(500);
response.end('Server Error!');
return;
}
var headers = {'Content-Type': mimeTypes[path.extname(lookup)]};
response.writeHead(200, headers);
response.end(data);
});
return;
}
response.writeHead(404);
response.end('Page Not Found');
});
}).listen(8080);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment