This repository has been archived by the owner on Apr 16, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.js
66 lines (49 loc) · 1.45 KB
/
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
'use strict'
const pino = require('pino')()
const log = require('pino-http')({logger: pino})
const http = require('http')
const https = require('https')
const fs = require('fs')
const mkdirp = require('mkdirp')
const path = require('path')
const port = process.env.PORT || 3000
const server = http.createServer(handle)
server.listen(port, err => {
if (err) return pino.error(err)
pino.info(`Ready at :${port}`)
})
function handle (req, res) {
log(req, res)
if (req.url === '/') {
res.write('ok')
res.end()
return
}
const localPath = `/tmp${req.url}`
fs.open(localPath, 'r', (err, fd) => {
if (err && err.code === 'ENOENT') {
pino.info('No local version present, fetching...')
const url = `https://s3.amazonaws.com${req.url}`
mkdirp.sync(path.dirname(localPath))
const localFile = fs.createWriteStream(localPath)
const get = https.get(url, proxyRes => {
res.writeHead(proxyRes.statusCode, proxyRes.headers)
proxyRes.pipe(res, {end: true})
proxyRes.pipe(localFile)
})
get.on('error', err => {
pino.error(err)
})
return
}
if (err) throw err
pino.info('Cached file found, sending ...')
const readStream = fs.createReadStream(undefined, {fd: fd})
const stat = fs.statSync(localPath)
res.writeHead(200, {
'Content-Type': 'application/x-gzip',
'Content-Length': stat.size
})
readStream.pipe(res, {end: true})
})
}