-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathserver.mjs
53 lines (50 loc) · 1.83 KB
/
server.mjs
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
import fs from 'fs';
import path from 'path';
import polka from 'polka';
import expose from './expose.js';
polka()
.get('/js/:file', (req, res) => {
const file = path.resolve(expose.__dirname, req.params.file);
let stream = fs.createReadStream(file);
stream.on('error', error => {
res.writeHead(404, {
'Content-Type': 'text/plain',
});
res.end('file not found');
});
stream.on('open', () => {
res.writeHead(200, {
'Content-Type': 'text/javascript',
'Cache-Control': 'public,max-age=31536000,immutable',
'Timing-Allow-Origin': '*',
'Access-Control-Allow-Credentials': 'true',
'Access-Control-Allow-Origin': '*',
});
stream.pipe(res);
});
stream.on('end', () => {
res.end();
});
})
.get('/', (req, res) => {
res.setHeader('Link', '</js/output-modules.mjs>; rel=preload; crossorigin=anonymous; as=script');
res.end(`
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Modules / No Modules Example</title>
<meta name="viewport" content="width=device-width,minimum-scale=1,initial-scale=1">
<script>!function(){var e=document,t=e.createElement("script");if(!("noModule"in t)&&"onbeforeload"in t){var n=!1;e.addEventListener("beforeload",function(e){if(e.target===t)n=!0;else if(!e.target.hasAttribute("nomodule")||!n)return;e.preventDefault()},!0),t.type="module",t.src=".",e.head.appendChild(t),t.remove()}}();</script>
<script type="module" crossorigin="anonymous" src="/js/output-modules.mjs"></script>
<script nomodule src="/js/output-nomodules.js"></script>
</head>
<body>
<p>Text below inserted via JS, you'll only get one value or the other.</p>
</body>
</html>
`);
})
.listen(3000).then(_ => {
console.log(`> Running on localhost:3000`);
});