-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathserver.js
More file actions
76 lines (65 loc) · 1.83 KB
/
server.js
File metadata and controls
76 lines (65 loc) · 1.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
const path = require('path');
const fs = require('fs');
const http = require('http');
const express = require('express');
const cors = require('cors');
const logger = require('morgan');
const debug = require('debug');
//
// this is cribbed from files generated by express-generator for a new app,
// principally ./bin/www and ./app.js.
//
// error listener
function onError(options, error) {
if (error.syscall !== 'listen') {
throw error;
}
const bind = typeof port === 'string'
? 'Pipe ' + options.port
: 'Port ' + options.port;
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}
// event listener
function onListening(server) {
const addr = server.address();
const bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
console.log(`Listening on ${bind}`);
debug('Listening on ' + bind);
}
function start(dir, options) {
const app = express();
app.use(express.json());
app.use(cors());
app.use(express.static(dir, {}));
app.use(logger('tiny'));
const server = http.createServer(app);
// Perform some basic checks to ensure we have a directory with something to serve
if (!fs.existsSync(path.resolve(dir))) {
console.log(`Directory "${dir}" does not exist.`);
return;
}
if (!fs.existsSync(path.resolve(dir, 'index.html'))) {
console.log(`Directory "${dir}" does not contain an index.html.`);
return;
}
server.listen(options.port);
server.on('error', (error) => onError(options, error));
server.on('listening', () => onListening(server));
}
module.exports = {
start,
};