Skip to content

Instantly share code, notes, and snippets.

@syuji-higa
Last active November 16, 2019 03:53
Show Gist options
  • Save syuji-higa/52479685a474e517248b8585f61957d0 to your computer and use it in GitHub Desktop.
Save syuji-higa/52479685a474e517248b8585f61957d0 to your computer and use it in GitHub Desktop.
Node.js - render HTML
'use strict'
const { readFile } = require('fs')
const Koa = require('koa')
const Router = require('koa-router')
require('colors')
const app = new Koa()
const router = new Router()
const readFileThunk = function(src) {
return new Promise(function (resolve, reject) {
readFile(src, { 'encoding': 'utf8' }, function (err, data) {
if(err) return reject(err)
resolve(data)
})
})
}
router
.get('/', async (ctx, next) => {
const { method, url } = ctx.request
console.log(`[${method}: ${url}]`.yellow)
ctx.body = await readFileThunk(`${__dirname}/views/viewer.html`)
await next()
})
app
.use(router.routes())
.use(router.allowedMethods())
const server = app.listen('3000', '127.0.0.1', () => {
const host = server.address().address
const port = server.address().port
console.log('listening at http://%s:%s', host, port)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment