huskee-install
Version:
Huskee server installer
49 lines (47 loc) • 1.52 kB
JavaScript
const path = require('path')
const Cache = require('./cache')
const fs = require('fs')
const zlib = require('zlib')
const mimeModule = require('./mime')
let cache = new Cache()
let mtimeCache = new Map()
const fsStatAsync = path => new Promise(resolve => {
fs.stat(path, (err, stats) => err ? resolve(0) : resolve(stats))
})
module.exports = async function _getStatic() {
const { req, res, fullPath, extname } = this
const { headers } = req
const mime = mimeModule.see(extname)
const stats = await fsStatAsync(fullPath)
if(!stats) return ''
const mtime = stats.mtime.toUTCString()
res.writeHead(200, {
'Content-Encoding': 'gzip',
'Content-Type': `${mime}`,
'Cache-Control': 'no-cache',
'Last-Modified': mtime
})
if(
headers['cache-control'] !== 'no-cache' &&
headers['cache-control'] !== 'max-age=0' &&
headers['if-modified-since'] &&
headers['if-modified-since'] == mtime
) {
return 'unchanged'
}
if(cache.get(fullPath) && mtime == mtimeCache.get(fullPath)) {
cache.get(fullPath).pipe(res)
return 'done'
}
const readStream = fs.createReadStream(fullPath)
const gzipping = readStream.pipe(zlib.createGzip())
mtimeCache.set(fullPath, mtime)
gzipping.on('finish', () => {
const caching = gzipping.pipe(cache.set(fullPath))
caching.on('finish', () => {
const returning = cache.get(fullPath).pipe(res)
returning.on('finish', () => res.end())
})
})
return 'done'
}