I'm using fastify's fastify-static plugin, and need to transform files that it is serving. For example, I'd like to replace "this-link" with "that-link". I've tried various fastify.addHook() events listed here, https://www.fastify.io/docs/latest/Hooks/, and the sensible one to me is the "onSend" where they demonstrate [string].replace(), but all have failed. For the onSend handler, the payload is not a mutable string, but instead it appears to be a PassThrough readable stream. With that in mind, I tried inspecting the data with payload.on('data', (chunk) => {...})
. That was insightful. I could see the file text, but I'm treading a bit deep into streams and fastify plugins and not sure how to proceed.
- Is there a simple way to transform responses before they are sent when using fastify-static? (Why are the documented addHook()'s failing?)
- Assuming I properly interpreted the payload as a readable stream, how can I transform that before fastify-static sends it?
An endpoint can send strings, buffer or streams.
So the
onSend
hook will receive one of those data type.As example:
fastify-static
sends files as a stream, so you would need to implement a Transform stream. Here a quick and dirty example assuming astatic/hello
file exists with content:As a suggestion, I would use a templating system from the point-of-view plugins, since it supports these kinds of features out of the box.