Nuxt/lib/core/server.js

86 lines
1.9 KiB
JavaScript
Raw Normal View History

2017-06-18 18:27:24 +00:00
import http from 'http'
import connect from 'connect'
import path from 'path'
import chalk from 'chalk'
class Server {
constructor (nuxt) {
this.nuxt = nuxt
2017-06-11 14:17:36 +00:00
this.options = nuxt.options
// Initialize
2017-06-15 22:19:53 +00:00
if (nuxt.initialized) {
// If nuxt already initialized
this._ready = this.ready().catch(this.nuxt.errorHandler)
} else {
// Wait for hook
this.nuxt.plugin('afterInit', () => {
this._ready = this.ready()
return this._ready
})
}
}
2017-06-15 22:28:08 +00:00
async ready () {
2017-06-15 22:19:53 +00:00
if (this._ready) {
return this._ready
}
this.app = connect()
this.server = http.createServer(this.app)
2017-06-15 22:19:53 +00:00
// Add Middleware
this.options.serverMiddleware.forEach(m => {
this.useMiddleware(m)
})
2017-06-15 22:19:53 +00:00
// 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))
}
2017-06-16 12:42:45 +00:00
m = 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
2017-06-15 14:59:26 +00:00
this.nuxt.ready()
2017-06-15 22:19:53 +00:00
.then(() => {
this.server.listen(port, host, () => {
let _host = host === '0.0.0.0' ? 'localhost' : host
// eslint-disable-next-line no-console
2017-06-18 17:53:01 +00:00
console.log('\n' + chalk.bold(chalk.bgBlue.black(' OPEN ') + chalk.blue(` http://${_host}:${port}\n`)))
2017-06-15 22:19:53 +00:00
})
2017-06-11 13:49:01 +00:00
})
2017-06-15 22:19:53 +00:00
.catch(this.nuxt.errorHandler)
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