Skip to content

Instantly share code, notes, and snippets.

@syuji-higa
Last active November 16, 2019 03:52
Show Gist options
  • Save syuji-higa/dffdf5f78ad38d899387aceabd669263 to your computer and use it in GitHub Desktop.
Save syuji-higa/dffdf5f78ad38d899387aceabd669263 to your computer and use it in GitHub Desktop.
Node.js - view server
'use strict'
const { join } = require('path')
const Koa = require('koa')
const Router = require('koa-router')
const serve = require('koa-static')
const views = require('co-views')
require('colors')
const CLIENT_PORT = 9999
const VIEWS_DIR = 'views'
const app = new Koa()
const router = new Router()
const render = views(join(__dirname, VIEWS_DIR), {
map: { html: 'html' }
})
router
.get('/', async (ctx, next) => {
const { method, url } = ctx.request
console.log(`[${method}: ${url}]`.yellow)
ctx.body = await render('viewer')
await next()
})
app
.use(router.routes())
.use(router.allowedMethods())
.use(serve(join(__dirname, VIEWS_DIR)))
const server = app.listen(CLIENT_PORT, '0.0.0.0', () => {
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