I have a NodeJS package, staticize, which takes an object of HTTP routes -> file locations, then serves them dynamically on each request.
Could I get some feedback on the latest rewrite of the main file? (Also available on GitHub here)
var fs = require('fs');
var mime = require('mime');
module.exports = function(app, routes) {
// loop through routes
for (var index in routes) {
// closure: route is the HTTP request route, path is the file path
(function (route, path) {
app.get(route, function(req, res) {
// create a readable stream
var stream = fs.createReadStream(path, {encoding: 'utf8'});
stream
.once('error', function() {
res.status(500).end('Server error.');
console.error('ERROR (staticize): Could not open readable stream to ' + path);
})
.once('readable', function() {
// create headers
var headers = {
'Content-Type': mime.lookup(path)
};
// write head then pipe response
res.writeHead(200, headers);
stream.pipe(res);
});
});
})(index, routes[index]);
}
};
It is called simply like this:
staticize(app, {
'/foo': '../test/foo/bar.txt',
'/foo/more': '../test/foo-extra/bar.txt'
});
I've tried to perfect it as much as possible, but I may have overlooked some things.