Last active
August 22, 2020 03:41
-
-
Save banyudu/b58e216537d641cbc9fc0fbb93038026 to your computer and use it in GitHub Desktop.
代理unpkg的资源
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const app = require('express')(); | |
| const path = require('path') | |
| const fs = require('fs') | |
| const { createProxyMiddleware } = require('http-proxy-middleware'); | |
| const mcache = require('memory-cache') | |
| const getCacheFilePath = req => path.join('cache', Buffer.from(req.originalUrl || req.url).toString('base64') ) | |
| app.use('/unpkg', (req, res, next) => { | |
| req.cacheFilePath = getCacheFilePath(req) | |
| const headers = mcache.get(req.cacheFilePath) | |
| fs.exists(req.cacheFilePath, (exists) => { | |
| if (exists && headers) { | |
| for (const key in headers) { | |
| res.header(key, headers[key]) | |
| } | |
| fs.createReadStream(req.cacheFilePath).pipe(res) | |
| } else { | |
| next() | |
| } | |
| }) | |
| }) | |
| app.use('/unpkg', createProxyMiddleware({ | |
| target: 'https://unpkg.com/', | |
| changeOrigin: true, | |
| pathRewrite: {'^/unpkg' : ''}, | |
| onProxyRes: (proxyRes, req, res) => { | |
| if (proxyRes.headers.location) { | |
| proxyRes.headers.location = '/unpkg' + proxyRes.headers.location | |
| } else { | |
| proxyRes.pipe(fs.createWriteStream(req.cacheFilePath)) | |
| mcache.put(req.cacheFilePath, proxyRes.headers, 24 * 60 * 60 * 1000) // cache header in memory for one day | |
| } | |
| } | |
| })); | |
| app.listen(process.env.MDF_PROXY_PORT || 3000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment