Skip to content

Instantly share code, notes, and snippets.

@commenthol
Last active September 19, 2018 16:00
Show Gist options
  • Save commenthol/29543b5392e4f9baa90a95aaa08b1b56 to your computer and use it in GitHub Desktop.
Save commenthol/29543b5392e4f9baa90a95aaa08b1b56 to your computer and use it in GitHub Desktop.
legacy server with logger, body-parser middlewares and connect runner
const http = require('http')
const logger = (req, res, next) => {
const time = Date.now()
res.on('finish', () => {
const {method, url, headers, body} = req
const {statusCode} = res
console.log('%s %s %s %s %j %s', method, url, statusCode, Date.now() - time, headers, JSON.stringify(body))
})
next()
}
const bodyParser = (req, res, next) => {
let body = ''
req.on('data', c => {
body += c.toString()
})
req.on('end', () => {
req.body = body
next()
})
req.on('error', (err) => {
next(err)
})
}
const connect = (...fns) => (req, res, done) => {
let i = 0
function run (err) {
const fn = fns[i++]
if (typeof fn === 'function') {
if (err) {
if (fn.length === 4) {
fn(err, req, res, (err) => run(err))
} else {
run(err)
}
} else {
if (fn.length === 4) {
run()
} else {
fn(req, res, (err) => run(err))
}
}
} else {
done && done(err)
}
}
run()
}
http.createServer(
connect(
logger,
bodyParser,
(req, res) => {
const {method, url, body} = req
console.log(method, url, body)
res.end()
},
(err, req, res, next) => {
console.error(err)
res.statusCode = 500
res.end()
}
)
).listen(3000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment