UNPKG

1.15 kBJavaScriptView Raw
1const express = require('express');
2const compression = require('compression');
3const serveIndex = require('serve-index');
4const chalk = require('chalk');
5
6class LocalServer {
7 constructor(root, host = 'localhost', port = 3000, debug = false) {
8 this.app = express();
9 this.host = host;
10 this.port = port;
11 this.server = null;
12 this.debug = debug;
13
14 this.app.use(compression());
15 this.app.use(serveIndex(root));
16 this.app.use(express.static(root));
17 }
18
19 listen() {
20 if (this.server !== null) throw new Error(`server is already running on port ${this.port}`);
21 this.server = this.app.listen(this.port, () => {
22 if (this.debug) {
23 process.stdout.write(
24 'IP: ' + this.server.address().address + '\n'+
25 'PORT: ' + this.server.address().port + '\n' +
26 '\n\n'
27 );
28 }
29
30 process.stdout.write(
31 chalk.inverse.bold(`Testing started on http://${this.host}:${this.port} `) + '\n\n'
32 );
33 });
34 }
35
36 close() {
37 if (this.server !== null) {
38 this.server.close(() => {});
39 this.server = null;
40 }
41 }
42}
43
44module.exports.LocalServer = LocalServer;