REserve offers a mechanism to capture the response stream and duplicate its content to another writable stream.
function capture (response: ServerResponse, stream: WritableStream): Promise<void>
Types definition for
capture
Important
The content is decoded if the content-encoding
header contains: gzip
, deflate
or br
(only one, no combination is supported).
Caution
Check the version of Node.js to enable br
compression support.
In the following example, three mappings are used :
- If the request resource exists in the
cache
folder , it is returned. - Otherwise, the second mapping captures and serializes locally the response returned by the last mapping.
- The last mapping redirects the request to an external site.
mappings: [{
match: /^\/(.*)/,
file: './cache/$1'
}, {
method: 'GET',
custom: async (request, response) => {
if (/\.(js|css|svg|jpg)$/.exec(request.url)) {
const cachePath = join(cacheBasePath, '.' + request.url)
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: 'http://your.website.domain/$1'
}]
Example of
capture
used to cache resources