Skip to content

Commit

Permalink
Check the existence of the gzipped path explicitly (#704)
Browse files Browse the repository at this point in the history
* Check the existance of the gzipped path explicitely.

* Fix a typo in the comments.

* Fix a typo.
  • Loading branch information
arunoda authored and rauchg committed Jan 9, 2017
1 parent 88e4adf commit d7eac7f
Showing 1 changed file with 17 additions and 6 deletions.
23 changes: 17 additions & 6 deletions server/render.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { join } from 'path'
import { createElement } from 'react'
import { renderToString, renderToStaticMarkup } from 'react-dom/server'
import send from 'send'
import fs from 'mz/fs'
import accepts from 'accepts'
import mime from 'mime-types'
import requireModule from './require'
Expand Down Expand Up @@ -148,19 +149,29 @@ export async function serveStaticWithGzip (req, res, path) {
return serveStatic(req, res, path)
}

const gzipPath = `${path}.gz`

try {
const gzipPath = `${path}.gz`
const contentType = mime.lookup(path) || 'application/octet-stream'
res.setHeader('Content-Type', contentType)
res.setHeader('Content-Encoding', 'gzip')
await serveStatic(req, res, gzipPath)
// We need to check the existance of the gzipPath.
// Getting `ENOENT` error from the `serveStatic` is inconsistent and
// didn't work on all the cases.
//
// And this won't give us a race condition because we know that
// we don't add gzipped files at runtime.
await fs.stat(gzipPath)
} catch (ex) {
if (ex.code === 'ENOENT') {
res.removeHeader('Content-Encoding')
// Seems like there's no gzipped file. Let's serve the uncompressed file.
return serveStatic(req, res, path)
}

throw ex
}

const contentType = mime.lookup(path) || 'application/octet-stream'
res.setHeader('Content-Type', contentType)
res.setHeader('Content-Encoding', 'gzip')
return serveStatic(req, res, gzipPath)
}

export function serveStatic (req, res, path) {
Expand Down

0 comments on commit d7eac7f

Please sign in to comment.