goldilocks.js/app.js

63 lines
1.5 KiB
JavaScript
Raw Normal View History

2015-06-24 21:36:17 +00:00
'use strict';
module.exports = function (opts) {
var finalhandler = require('finalhandler');
var serveStatic = require('serve-static');
var serveIndex = require('serve-index');
var serve = serveStatic(opts.public);
var index = serveIndex(opts.public);
2015-06-30 23:11:01 +00:00
var content = opts.content;
2015-06-24 21:36:17 +00:00
return function (req, res) {
2015-06-30 23:11:01 +00:00
if (content && '/' === req.url) {
// res.setHeader('Content-Type', 'application/octet-stream');
res.end(content);
return;
}
2015-06-24 21:36:17 +00:00
var done = finalhandler(req, res);
2015-12-06 06:43:33 +00:00
var livereload = '';
var addLen = 0;
if (opts.livereload) {
livereload = '<script src="//'
+ (res.getHeader('Host') || opts.servername).split(':')[0]
2016-10-06 22:42:38 +00:00
+ ':' + opts.lrPort + '/livereload.js?snipver=1"></script>';
2015-12-06 06:43:33 +00:00
addLen = livereload.length;
}
res.__write = res.write;
res.write = function (data, enc, cb) {
if (this.headersSent) {
this.__write(data, enc, cb);
2015-12-06 06:43:33 +00:00
return;
}
if (!/html/i.test(this.getHeader('Content-Type'))) {
this.__write(data, enc, cb);
return;
}
if (this.getHeader('Content-Length')) {
this.setHeader('Content-Length', this.getHeader('Content-Length') + addLen);
}
this.__write(livereload);
this.__write(data, enc, cb);
};
2016-08-06 20:15:12 +00:00
function serveStatic() {
serve(req, res, function (err) {
2016-08-06 18:34:15 +00:00
if (err) { return done(err); }
2016-08-06 20:15:12 +00:00
index(req, res, done);
2016-08-06 18:34:15 +00:00
});
2016-08-06 20:15:12 +00:00
}
if (opts.expressApp) {
opts.expressApp(req, res, serveStatic);
}
else {
serveStatic();
}
2015-06-24 21:36:17 +00:00
};
};