forked from heroku/node-js-sample
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathweb.js
More file actions
45 lines (37 loc) · 1.21 KB
/
web.js
File metadata and controls
45 lines (37 loc) · 1.21 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
const fs = require('node:fs');
const path = require('node:path');
const http = require('node:http');
const indexPath = path.join(__dirname, 'index.html');
const serveFile = (response, filePath, contentType) => {
const data = fs.readFileSync(filePath, 'utf-8');
response.writeHead(200, { 'Content-Type': contentType });
response.end(data);
};
const createServer = () => http.createServer((request, response) => {
if (request.url === '/' || request.url === '/index.html') {
serveFile(response, indexPath, 'text/html; charset=utf-8');
return;
}
if (request.url.startsWith('/assets/')) {
const assetPath = path.join(__dirname, request.url);
if (!fs.existsSync(assetPath)) {
response.writeHead(404);
response.end('Not found');
return;
}
const contentType = assetPath.endsWith('.css')
? 'text/css; charset=utf-8'
: 'application/javascript; charset=utf-8';
serveFile(response, assetPath, contentType);
return;
}
response.writeHead(404);
response.end('Not found');
});
if (require.main === module) {
const port = process.env.PORT || 5000;
createServer().listen(port, () => {
console.log(`Listening on ${port}`);
});
}
module.exports = { createServer };