-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
Server.js
85 lines (73 loc) 路 2.27 KB
/
Server.js
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
77
78
79
80
81
82
83
84
85
const http = require('http');
const path = require('path');
const url = require('url');
const serveStatic = require('serve-static');
const getPort = require('get-port');
const serverErrors = require('./utils/customErrors').serverErrors;
function middleware(bundler) {
const serve = serveStatic(bundler.options.outDir, {index: false});
return function(req, res, next) {
// Wait for the bundler to finish bundling if needed
if (bundler.pending) {
bundler.once('bundled', respond);
} else {
respond();
}
function respond() {
if (bundler.errored) {
return send500();
} else if (!req.url.startsWith(bundler.options.publicURL)) {
// If the URL doesn't start with the public path, send the main HTML bundle
return sendIndex();
} else {
// Otherwise, serve the file from the dist folder
req.url = req.url.slice(bundler.options.publicURL.length);
return serve(req, res, send404);
}
}
function sendIndex() {
// If the main asset is an HTML file, serve it
if (bundler.mainAsset.type === 'html') {
req.url = `/${bundler.mainAsset.generateBundleName(true)}`;
serve(req, res, send404);
} else {
send404();
}
}
function send500() {
res.setHeader('Content-Type', 'text/plain; charset=utf-8');
res.writeHead(500);
res.end('馃毃 Build error, check the console for details.');
}
function send404() {
if (next) {
return next();
}
res.writeHead(404);
res.end();
}
};
}
async function serve(bundler, port) {
let freePort = await getPort({port});
let server = http.createServer(middleware(bundler)).listen(freePort);
server.on('error', err => {
bundler.logger.error(new Error(serverErrors(err, server.address().port)));
});
server.once('listening', connection => {
let addon =
server.address().port !== port
? `- ${bundler.logger.chalk.red(
`configured port ${port} could not be used.`
)}`
: '';
bundler.logger.persistent(
`Server running at ${bundler.logger.chalk.cyan(
`http://localhost:${server.address().port}`
)} ${addon}\n`
);
});
return server;
}
exports.middleware = middleware;
exports.serve = serve;