2017-03-29 17:50:05 +00:00
|
|
|
let finalhandler = require('finalhandler');
|
|
|
|
let http = require('http');
|
|
|
|
let serveStatic = require('serve-static');
|
2018-07-26 17:13:18 +00:00
|
|
|
const {canonicalHost, defaultHost, dockerHostSwap} = require('../../utils/host');
|
2017-12-17 23:34:41 +00:00
|
|
|
require('http-shutdown').extend();
|
2016-08-21 15:02:50 +00:00
|
|
|
|
2017-03-30 11:12:39 +00:00
|
|
|
class Server {
|
|
|
|
constructor(options) {
|
|
|
|
this.dist = options.dist || 'dist/';
|
|
|
|
this.port = options.port || 8000;
|
2018-07-26 17:13:18 +00:00
|
|
|
this.hostname = dockerHostSwap(options.host) || defaultHost;
|
2017-03-30 11:12:39 +00:00
|
|
|
this.logger = options.logger;
|
|
|
|
}
|
2016-08-21 15:02:50 +00:00
|
|
|
|
2017-03-30 11:12:39 +00:00
|
|
|
start(callback) {
|
2017-12-18 00:18:35 +00:00
|
|
|
if (this.server && this.server.listening) {
|
2018-07-26 17:13:18 +00:00
|
|
|
this.logger.warn(__("a webserver is already running at") +
|
|
|
|
" " +
|
|
|
|
("http://" + canonicalHost(this.hostname) +
|
|
|
|
":" + this.port).bold.underline.green);
|
2017-12-18 00:18:35 +00:00
|
|
|
if (callback) {
|
|
|
|
callback();
|
|
|
|
}
|
|
|
|
return;
|
|
|
|
}
|
2017-03-30 11:12:39 +00:00
|
|
|
let serve = serveStatic(this.dist, {'index': ['index.html', 'index.htm']});
|
2016-08-21 15:02:50 +00:00
|
|
|
|
2017-12-17 23:34:41 +00:00
|
|
|
this.server = http.createServer(function onRequest(req, res) {
|
2017-03-30 11:12:39 +00:00
|
|
|
serve(req, res, finalhandler(req, res));
|
2017-12-17 23:34:41 +00:00
|
|
|
}).withShutdown();
|
2016-08-21 15:02:50 +00:00
|
|
|
|
2018-07-26 17:13:18 +00:00
|
|
|
this.logger.info(__("webserver available at") +
|
|
|
|
" " +
|
|
|
|
("http://" + canonicalHost(this.hostname) +
|
|
|
|
":" + this.port).bold.underline.green);
|
2017-12-17 23:34:41 +00:00
|
|
|
this.server.listen(this.port, this.hostname);
|
|
|
|
if (callback) {
|
|
|
|
callback();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
stop(callback) {
|
2017-12-18 00:18:35 +00:00
|
|
|
if (!this.server || !this.server.listening) {
|
2018-05-08 21:49:46 +00:00
|
|
|
this.logger.warn(__("no webserver is currently running"));
|
2017-12-18 00:18:35 +00:00
|
|
|
if (callback) {
|
|
|
|
callback();
|
|
|
|
}
|
|
|
|
return;
|
|
|
|
}
|
2017-12-17 23:34:41 +00:00
|
|
|
this.server.shutdown(function() {
|
|
|
|
if (callback) {
|
|
|
|
callback();
|
|
|
|
}
|
|
|
|
});
|
2017-03-30 11:12:39 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
}
|
2016-08-21 15:02:50 +00:00
|
|
|
|
|
|
|
module.exports = Server;
|