capture
helperREserve 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
orbr
(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 :
cache
folder , it is returned.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