2

I'm new to node/express, so there's (hopefully) an obvious answer that I'm missing.

There's a middleware for transforming static content: https://www.npmjs.com/package/connect-static-transform/. The transformation function looks like:

transform: function (path, text, send) {
   send(text.toUpperCase(), {'Content-Type': 'text/plain'});
}

So, that's great for transforming the content before serving, but it doesn't let me look at query parameters.

This answer shows how to do it Connect or Express middleware to modify the response.body:

function modify(req, res, next){
   res.body = res.body + "modified";
   next();
}

But I can't figure out how to get it to run with static file content. When I run it res.body is undefined.

Is there some way to get a middleware to run after express.static?

My use case is that I want to serve files from disk making a small substitution of some text based on the value of a query parameter. This would be easy with server-side templating, like Flask. But I want the user to be able to do a simple npm-install and start up a tiny server to do this. Since I'm new to node and express, I wanted to save myself the bother of reading the url, locating the file on disk and reading it. But it's becoming clear that I wasted much more time trying this approach.

Community
  • 1
  • 1
Sigfried
  • 2,943
  • 3
  • 31
  • 43
  • 1
    either you need `static`, which means you are **not** going to do *any* modification, or you need specialized serving with req/res objects, but using static-transform is literally perverse. If you need headers sent based on mime-type, then [tell express to do so](http://expressjs.com/api.html) via a setHeaders option. – Mike 'Pomax' Kamermans May 29 '15 at 20:28

2 Answers2

3

The answer appears to be "There is no answer." (As suggested by Pomax in the comment.) This is really annoying. It didn't take me too long to figure out how to serve and transform files myself, but now I'm having to figure out error handling. A million people have already written this code.

Sigfried
  • 2,943
  • 3
  • 31
  • 43
0

You can create middleware that only does transformation of body chunks as they are written with res.write or res.end or whatever.

For example:

const CSRF_RE = /<meta name="csrf-token" content="(.*)"([^>]*)?>/

function transformMiddleware (req, res, next) {
  const _write = res.write
  res.write = function(chunk, encoding) {
    if (chunk.toString().indexOf('<meta name="csrf-token"') === -1) {
      _write.call(res, chunk, encoding)
    } else {
      const newChunk = chunk.toString().replace(CSRF_RE, `<meta name="csrf-token" content="${req.csrfToken()}">`)
      _write.call(res, newChunk, encoding)
    }
  }
  next()
}
Evgeny
  • 6,533
  • 5
  • 58
  • 64