70 lines
2.4 KiB
JavaScript
Raw Normal View History

2017-03-30 02:50:05 +09:00
let finalhandler = require('finalhandler');
const fs = require('../../core/fs.js');
2017-03-30 02:50:05 +09:00
let http = require('http');
let serveStatic = require('serve-static');
const {canonicalHost, defaultHost, dockerHostSwap} = require('../../utils/host');
const opn = require('opn');
const utils = require('../../utils/utils.js');
2017-12-17 18:34:41 -05:00
require('http-shutdown').extend();
2016-08-21 11:02:50 -04:00
require('ejs');
const embark_building_placeholder = require('../code_generator/code_templates/embark-building-placeholder.html.ejs');
2017-03-30 20:12:39 +09:00
class Server {
constructor(options) {
this.dist = options.dist || 'dist/';
this.port = options.port || 8000;
this.hostname = dockerHostSwap(options.host) || defaultHost;
this.isFirstStart = true;
this.opened = false;
2017-03-30 20:12:39 +09:00
}
2016-08-21 11:02:50 -04:00
2017-03-30 20:12:39 +09:00
start(callback) {
if (this.server && this.server.listening) {
2018-08-10 15:09:56 +01:00
let message = __("a webserver is already running at") + " " +
("http://" + canonicalHost(this.hostname) +
":" + this.port).bold.underline.green;
return callback(null, message);
}
2017-03-30 20:12:39 +09:00
let serve = serveStatic(this.dist, {'index': ['index.html', 'index.htm']});
2016-08-21 11:02:50 -04:00
2017-12-17 18:34:41 -05:00
this.server = http.createServer(function onRequest(req, res) {
2017-03-30 20:12:39 +09:00
serve(req, res, finalhandler(req, res));
2017-12-17 18:34:41 -05:00
}).withShutdown();
2016-08-21 11:02:50 -04:00
if (this.isFirstStart) {
const html = embark_building_placeholder({buildingMsg: __('Embark is building, please wait...')});
fs.mkdirpSync(this.dist); // create dist/ folder if not already exists
fs.writeFileSync(utils.joinPath(this.dist, 'index.html'), html);
this.isFirstStart = false;
}
2018-08-23 15:11:43 -04:00
this.server.listen(this.port, this.hostname, () => {
this.port = this.server.address().port;
callback(null, __("webserver available at") +
" " +
("http://" + canonicalHost(this.hostname) +
":" + this.port).bold.underline.green, this.port);
if (!this.opened) {
2018-08-31 11:16:57 -05:00
// fail silently, e.g. in a docker container, by cacthing promise
// rejection w/ a noop
opn(`http://${canonicalHost(this.hostname)}:${this.port}`)
.catch(function () {});
this.opened = true;
}
2018-08-23 15:11:43 -04:00
});
2017-12-17 18:34:41 -05:00
}
stop(callback) {
if (!this.server || !this.server.listening) {
2018-08-10 15:09:56 +01:00
return callback(null, __("no webserver is currently running"));
}
2017-12-17 18:34:41 -05:00
this.server.shutdown(function() {
2018-08-10 15:09:56 +01:00
callback(null, __("Webserver stopped"));
2017-12-17 18:34:41 -05:00
});
2017-03-30 20:12:39 +09:00
}
}
2016-08-21 11:02:50 -04:00
module.exports = Server;