Skip to content

Instantly share code, notes, and snippets.

@ArnaudBuchholz
Created May 25, 2020 02:21
Show Gist options
  • Save ArnaudBuchholz/d35ac4bc36ad1823c0eec67b255de475 to your computer and use it in GitHub Desktop.
Save ArnaudBuchholz/d35ac4bc36ad1823c0eec67b255de475 to your computer and use it in GitHub Desktop.
const { createWriteStream, mkdir } = require('fs')
const { dirname, join } = require('path')
const { capture, log, serve } = require('..')
const mkdirAsync = require('util').promisify(mkdir)
const cacheBasePath = join(__dirname, 'cache')
// Should wait for completion
mkdirAsync(cacheBasePath, { recursive: true })
log(serve({
port: 8080,
mappings: [{
match: /^http:\/\/([^/]*)\/(.*)/,
file: './cache/$1/$2',
'ignore-if-not-found': true
}, {
method: 'GET',
match: /^http:\/\/([^/]*)\/(.*)/,
custom: async (request, response, server, path) => {
if (/\.(ico|js|css|svg|jpe?g)$/.exec(path)) {
const cachePath = join(cacheBasePath, server, path)
const cacheFolder = dirname(cachePath)
await mkdirAsync(cacheFolder, { recursive: true })
const file = createWriteStream(cachePath) // auto closed
capture(response, file)
.catch(reason => {
console.error(`Unable to cache ${cachePath}`, reason)
})
}
}
}, {
match: /^(.*)/,
url: '$1'
}]
}), process.argv.includes('--verbose'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment