lukeed / sirv

An optimized middleware & CLI application for serving static files~!
MIT License
1.06k stars 56 forks source link

Add "watch" mode to update filesystem cache #157

Closed stevenle closed 8 months ago

stevenle commented 8 months ago

The notes about {dev: true} make it seem like it creates a lot of overhead on every request. Is it possible to improve dev performance by adding a {watch: true} mode that uses a cache and runs a filesystem watcher (e.g. chokidar) which updates the cache whenever files change?

lukeed commented 8 months ago

The notes about {dev: true} make it seem like it creates a lot of overhead on every request

It does. It touches the filesystem on every request, and perhaps multiple times depending on your path/structure.

Is it possible to improve dev performance by adding a ... chokidar

This is significantly more overhead & would ultimately be far more memory & CPU intensive than the current dev:true approach. If you want to use a cache, then dev: false and you'll be file-serving as fast as possible. If you really want to reload the cache on file change (I highly suggest dev: true cuz it's rly not that much penalty, or you can do...) then you can use a file watcher to rebuild the sirv('...', { dev: false }) handler on file change. It'll fully rebuild the cache but a full-build is fast (to a point):

let options = {
  dev: false,
  // ...
}

let handler = sirv('path/to/dir', options);

chokidar.watch('path/to/dir').on('all', (event, path) => {
  console.log(event, path);
  handler = sirv('path/to/dir', options);
});

polka()
  .use('/assets', (req, res, next) => {
    return handler(req, res, next);
  })
  // ...
stevenle commented 8 months ago

Perfect response, thanks for the added direction @lukeed . Going to give both scenarios a try, our system already has a filewatcher so it's not much overhead for us to rebuild the cache if an "asset file" change is detected.