forked from msironi/expr-eval
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathserve-sample.cjs
More file actions
62 lines (52 loc) · 2.1 KB
/
Copy pathserve-sample.cjs
File metadata and controls
62 lines (52 loc) · 2.1 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
// Minimal static file server for the Monaco sample (no extra deps)
const http = require('http');
const fs = require('fs');
const path = require('path');
const root = path.resolve(__dirname, '../../');
const port = process.env.PORT ? Number(process.env.PORT) : 8080;
const mime = {
'.html': 'text/html; charset=utf-8',
'.js': 'application/javascript; charset=utf-8',
'.mjs': 'application/javascript; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.map': 'application/json; charset=utf-8',
'.json': 'application/json; charset=utf-8'
};
function send(res, status, body, headers = {}) {
res.writeHead(status, {'Content-Length': Buffer.byteLength(body), ...headers});
res.end(body);
}
const server = http.createServer((req, res) => {
let urlPath = decodeURIComponent(req.url || '/');
// Strip query string
const queryIndex = urlPath.indexOf('?');
if (queryIndex !== -1) {
urlPath = urlPath.substring(0, queryIndex);
}
if (urlPath === '/' || urlPath === '/index.html') {
urlPath = 'samples/language-service-sample/index.html';
} else if (urlPath === '/styles.css' || urlPath === '/app.js' || urlPath === '/examples.js') {
// Serve sample-specific files from the sample folder
urlPath = 'samples/language-service-sample' + urlPath;
}
const filePath = path.join(root, urlPath);
// OBVIOUSLY THIS IS NOT SECURE! DO NOT USE IN UNSAFE ENVIRONMENTS!
fs.stat(filePath, (err, stat) => {
if (err) {
return send(res, 404, 'Not found');
}
if (stat.isDirectory()) {
return send(res, 403, 'Forbidden');
}
const ext = path.extname(filePath).toLowerCase();
const type = mime[ext] || 'application/octet-stream';
fs.readFile(filePath, (err2, data) => {
if (err2) return send(res, 500, 'Server error');
res.writeHead(200, {'Content-Type': type, 'Content-Length': data.length});
res.end(data);
});
});
});
server.listen(port, () => {
console.log(`[expr-eval] Sample server running at http://localhost:${port}`);
});