1
0
mirror of https://github.com/nuxt/nuxt.git synced 2024-12-11 23:07:16 +00:00
Nuxt/lib/server.js

67 lines
1.5 KiB
JavaScript
Raw Normal View History

'use strict'
const http = require('http')
const connect = require('connect')
const path = require('path')
class Server {
constructor (nuxt) {
this.nuxt = nuxt
// Initialize
this.app = connect()
this.server = http.createServer(this.app)
this.nuxt.ready()
.then(() => {
// Add Middleware
this.nuxt.options.serverMiddleware.forEach(m => {
this.useMiddleware(m)
})
// Add default render middleware
this.useMiddleware(this.render.bind(this))
})
return this
}
useMiddleware (m) {
// Require if needed
if (typeof m === 'string') {
let src = m
2017-05-21 17:18:48 +00:00
// Using ~ or ./ shorthand to resolve from project srcDir
if (src.indexOf('~') === 0 || src.indexOf('./') === 0) {
src = path.join(this.nuxt.options.srcDir, src.substr(1))
}
// eslint-disable-next-line no-eval
m = eval('require')(src)
}
if (m instanceof Function) {
this.app.use(m)
} else if (m && m.path && m.handler) {
this.app.use(m.path, m.handler)
}
}
render (req, res, next) {
this.nuxt.render(req, res)
return this
}
listen (port, host) {
2017-06-11 13:49:01 +00:00
host = host || 'localhost'
port = port || 3000
this.nuxt.ready()
.then(() => {
this.server.listen(port, host, () => {
2017-06-11 13:49:01 +00:00
let _host = host === '0.0.0.0' ? 'localhost' : host
console.log('Ready on http://%s:%s', _host, port) // eslint-disable-line no-console
})
})
return this
}
2016-12-09 22:07:18 +00:00
close (cb) {
return this.server.close(cb)
}
}
2017-01-11 19:14:59 +00:00
export default Server