Skip to content

Instantly share code, notes, and snippets.

@lagden
Created November 10, 2016 06:23
Show Gist options
  • Save lagden/c31461e41be104023288359c94f1c9f2 to your computer and use it in GitHub Desktop.
Save lagden/c31461e41be104023288359c94f1c9f2 to your computer and use it in GitHub Desktop.
Puro Server - Node.js
'use strict'
const fs = require('fs')
const path = require('path')
const http = require('http')
const url = require('url')
const crypto = require('crypto')
const mimeTypes = require('mime-types')
const debug = require('debug')
const porta = process.env.PORT || 3032
const error = debug('site:error')
const log = debug('site:log')
const www = path.join(__dirname, 'public')
const server = http.createServer()
server
.on('request', (req, res) => {
const u = url.parse(req.url)
const data = []
let file = u.pathname
let contentType = mimeTypes.lookup(file)
if (contentType === false) {
file = `${file}.html`
contentType = mimeTypes.lookup(file)
}
fs
.createReadStream(path.join(www, file))
.on('data', chunk => {
data.push(chunk)
})
.on('end', () => {
const buffer = Buffer.concat(data)
const hash = crypto.createHash('sha256').update(buffer.toString('hex')).digest('hex')
const header = {
ETag: hash,
'Cache-Control': 'public, no-cache',
'Content-Type': contentType
}
res.writeHead(200, header)
res.write(buffer)
res.end()
})
.on('error', err => {
error(err.message)
fs.createReadStream(path.join(www, '404.html')).pipe(res)
})
})
.on('error', (err, socket) => {
error(err.message)
socket.end('HTTP/1.1 400 Bad Request\r\n\r\n')
})
.listen(porta, () => {
log(porta)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment