forked from jamesshore/lets_code_javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp_server.js
More file actions
54 lines (42 loc) · 1.4 KB
/
Copy pathhttp_server.js
File metadata and controls
54 lines (42 loc) · 1.4 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
// Copyright (c) 2017 Titanium I.T. LLC. All rights reserved. For license, see "README" or "LICENSE" file.
(function() {
"use strict";
const http = require("http");
const fs = require("fs");
const send = require("send");
const util = require("util");
module.exports = class HttpServer {
constructor(contentDir, notFoundPageToServe) {
this._httpServer = http.createServer();
handleHttpRequests(this._httpServer, contentDir, notFoundPageToServe);
}
start(portNumber) {
const listen = util.promisify(this._httpServer.listen.bind(this._httpServer));
return listen(portNumber);
}
stop() {
const close = util.promisify(this._httpServer.close.bind(this._httpServer));
return close();
}
getNodeServer() {
return this._httpServer;
}
};
function handleHttpRequests(httpServer, contentDir, notFoundPageToServe) {
httpServer.on("request", function(request, response) {
send(request, request.url, { root: contentDir }).on("error", handleError).pipe(response);
function handleError(err) {
if (err.status === 404) serveErrorFile(response, 404, contentDir + "/" + notFoundPageToServe);
else throw err;
}
});
}
function serveErrorFile(response, statusCode, file) {
response.statusCode = statusCode;
response.setHeader("Content-Type", "text/html; charset=UTF-8");
fs.readFile(file, function(err, data) {
if (err) throw err;
response.end(data);
});
}
}());