forked from angular/angular
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsimple-server.js
45 lines (39 loc) · 1008 Bytes
/
simple-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
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
const http = require('http');
const path = require('path');
const fs = require('fs');
let server;
const localFolder = __dirname;
function writeNotFound(res) {
res.writeHead(404, {'Content-Type': 'text/html'});
res.end('<h1>404, Not Found!</h1>');
}
function requestHandler(req, res) {
if (req.url === '/close') {
res.end('server closing');
setTimeout(() => {
process.exit(0);
}, 1000);
} else {
const file = path.resolve(localFolder, req.url);
if (!file.startsWith(localFolder + '/')) {
writeNotFound(res);
return;
}
fs.readFile(file, function (err, contents) {
if (!err) {
res.end(contents);
} else {
writeNotFound(res);
return;
}
});
}
}
server = http.createServer(requestHandler).listen(8080);