expressjs / express

Fast, unopinionated, minimalist web framework for node.

Home Page:https://expressjs.com

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Augment file before sending with .sendFile

kevincolten opened this issue · comments

Is there a way to intercept and augment the file being sent with res.sendFile()? I'd like to use .sendFile over just using .send because I have a dual server-based / react application, and I use the root option to toggle between.

Express uses send to pipe file data to the response stream.
If you need to make changes to the contents of the file in any way (append/prepend/replace) it makes more sense to use res.send.
However, if you need to make changes to the response (as in setting headers, or listening to response stream events), this is possible with send but not in express. All it would take to make these available is to return lib/response.js#449. Usage would be:

const respStream = res.sendfile(....)
respStream.on('stream', listener)

I was able to accomplish the behavior I needed by swapping out the send library in https://github.com/expressjs/express/blob/master/lib/response.js#L32 with send-transform. Now, along with replacestream, I can pass in an additional transform option and use it like so

const replaceStream = require('replacestream');
//...
  return res.sendFile('app.html', {
    root: './build',
    transform: (stream) => stream.pipe(replaceStream('hello', 'world'))
  });