const fs = require('fs')
const path = require('path')
const mime = require('mime-types')

const { getElapsedTime } = require('../dates')

module.exports = (req, res, next, {config, eventEmitter, log, bidCookieDetails}) => {
  const opts = req.upstream.upstream.options
  const file = path.join(opts.path, opts.file)

  res.setHeader('content-type', mime.lookup(opts.file))

  if (typeof opts.download === 'boolean' && opts.download) {
    res.setHeader('content-disposition', 'attachment; filename=' + opts.file)

    fs.readFile(file, opts.encoding, (err, data) => {
      const duration = getElapsedTime(req.startTime)

      if (err) {
        eventEmitter.emit('servingFileError', err, req.upstreamm, duration)
      } else {
        eventEmitter.emit('servingFile', req.upstreamm, duration)
      }

      res.send(data)
    })
  } else {
    fs.createReadStream(file).pipe(res)
  }
}

@@ -229,19 +229,53 @@
 nst 
+%7B startTime, upstream %7D = req%0A  const 
 opts = 
-req.
 upst
@@ -344,16 +344,269 @@
 .file)%0A%0A
+  const emitServingEvent = (err) =%3E %7B%0A    const duration = getElapsedTime(startTime)%0A%0A    if (err) %7B%0A      eventEmitter.emit('servingFileError', err, upstream, duration)%0A    %7D else %7B%0A      eventEmitter.emit('servingFile', upstream, duration)%0A    %7D%0A  %7D%0A%0A
   res.se
@@ -858,153 +858,70 @@
     
-const duration = getElapsedTime(req.startTime)%0A%0A      if (err) %7B%0A        eventEmitter.emit('servingFileError', err, req.upstreamm, duration
+emitServingEvent(err)%0A      res.send(err ? 500 : data
 )%0A    
+%7D)%0A
   %7D 
@@ -935,117 +935,26 @@
     
-   
- eventEmitter.
 emit
-('s
+S
 erving
-File', req.upstreamm, duration)%0A      %7D%0A%0A      res.send(data)%0A    %7D)%0A  %7D else %7B
+Event()
 %0A   

Fix event parameter. Send 500 when file not found