forked from npm/make-fetch-happen
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.js
More file actions
45 lines (38 loc) · 1.17 KB
/
Copy pathproxy.js
File metadata and controls
45 lines (38 loc) · 1.17 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 http = require('http')
const https = require('https')
/**
* Proxy GET requests to registry.npmjs.org but respond using chunked-encoding
* `npm install <package>` will fail with this registry.
*/
// different sizes will reproduce the issue, but large sizes will not.
const size = 0x4000
const host = 'https://registry.npmjs.com'
http.createServer(async (req, res) => {
if (req.method != 'GET') {
console.log('reject', { method: req.method, url: req.url })
res.writeHead(404)
res.end()
return
}
// forward to npm
https.get(host + req.url, async proxyRes => {
const {statusCode, statusMessage, headers} = proxyRes
// remove content-length so the server uses chunked encoding.
delete headers['content-length']
res.writeHead(statusCode, statusMessage, headers)
const buffer = await collect(proxyRes)
for (let i = 0; i < buffer.length; i += size) {
res.write(buffer.slice(i, i+size));
}
res.end()
})
}).listen(4000, function () {
console.log(this.address())
})
async function collect (stream) {
const buffers = [];
for await (const chunk of stream) {
buffers.push(chunk)
}
return Buffer.concat(buffers)
}