I am using fs.createReadStream() to read files, and then pipe them to the response.
I want to add a small Javascript function when I'm serving HTML files.
The only way I can think of is to read the file into a string, append the text to the string, and then stream the string to the response, but I think there could be a better/faster way to do this.
Is there a way for me to append the text to the file on the go?
After @Matthew Bakaitis's suggestion to use
throughand after reading for a while about it and checking the issues on github, I foundthrough's developer recommendingthrough2for a case similar to mine.Better implementation using
finishcallbackOld Implementation
This is how I implemented the solution:
The option
decodeStringsmust be set tofalseso that the chunk of data is a string and not a buffer. This is related to thetransformfunction of thestreamapi, not to through2.More info on
transform