expressjs / serve-static

Serve static files
MIT License
1.39k stars 228 forks source link

async setHeaders callback #21

Closed amasad closed 9 years ago

amasad commented 9 years ago

Most API's in express (and node) are async, but setHeaders callback here isn't. Here is a current use case that I have:

setHeaders: function(path, res) {
  fs.stat(path, (e, stat) => res.set('X-Raw-Length', stat.size));
}

I'm doing this to show a progress bar on the client-side when loading a big resource. Content-length won't work when the content is gzipped.

Of course, this doesn't work because by the time fs.stat comes back the response might have ended.

dougwilson commented 9 years ago

The way the send module works, it is just sync. Besides, the Content-Length header at this time is never the gzip'd length, always that from the disk, as this module and below does not gzip compression, so I'm not sure why you'd have to worry about getting the gzip'd length.

But even then, it looks like you just want to do something using the file's stat, which is actually the third argument. Could you do this?

setHeaders: function(res, path, stat) {
  res.set('X-Raw-Length', stat.size)
}
amasad commented 9 years ago

I use the compression module and the Content-Length is the gzip'd length. Also generally Content-Length wouldn't be reliable for my use case because some files would be streamed (Transfer-Encoding:chunked).

But this works perfectly! Thanks for the super quick reply. I'll update the documentation to add the stat arg.

dougwilson commented 9 years ago

Ah. I took a closer look into the send module and see that it doesn't even set the Content-Length until after the setHeaders anyway (this isn't really an issue, because, really, it's for setting headers in a particular pipeline, not really for altering headers).

Ans the reason it's sync instead of async is because send is a stream and this function is run as a EE listener, and EE listeners are only sync in Node.js, there is no async version of listeners, haha.

But thanks for the docs contribution, and I'm glad we could solve your problem with something that was just accidentally not documented (it's documented all the way down in send module)!

amasad commented 9 years ago

Happy to help. These projects are getting even better than last time I used them. You seem to run a tight ship :)