2017-06-18 18:27:24 +00:00
|
|
|
import http from 'http'
|
|
|
|
import chalk from 'chalk'
|
2016-11-09 22:59:41 +00:00
|
|
|
|
|
|
|
class Server {
|
|
|
|
constructor (nuxt) {
|
2016-11-16 17:41:09 +00:00
|
|
|
this.nuxt = nuxt
|
2017-06-11 14:17:36 +00:00
|
|
|
this.options = nuxt.options
|
|
|
|
|
2017-05-12 10:22:06 +00:00
|
|
|
// Initialize
|
2017-06-19 15:47:31 +00:00
|
|
|
/* istanbul ignore if */
|
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-19 23:15:57 +00:00
|
|
|
|
|
|
|
// Stop server on nuxt.close()
|
|
|
|
this.nuxt.plugin('close', () => this.close())
|
2017-06-15 22:19:53 +00:00
|
|
|
}
|
|
|
|
|
2017-06-15 22:28:08 +00:00
|
|
|
async ready () {
|
2017-06-19 15:47:31 +00:00
|
|
|
/* istanbul ignore if */
|
2017-06-15 22:19:53 +00:00
|
|
|
if (this._ready) {
|
|
|
|
return this._ready
|
|
|
|
}
|
|
|
|
|
2017-06-19 23:15:57 +00:00
|
|
|
this.render = this.nuxt.renderer.app
|
|
|
|
this.server = http.createServer(this.render)
|
2017-06-15 22:19:53 +00:00
|
|
|
|
2016-11-16 17:41:09 +00:00
|
|
|
return this
|
|
|
|
}
|
|
|
|
|
2016-11-09 22:59:41 +00:00
|
|
|
listen (port, host) {
|
2017-06-11 13:49:01 +00:00
|
|
|
host = host || 'localhost'
|
2016-11-09 22:59:41 +00:00
|
|
|
port = port || 3000
|
2017-06-19 23:15:57 +00:00
|
|
|
return this.ready()
|
2017-06-15 22:19:53 +00:00
|
|
|
.then(() => {
|
|
|
|
this.server.listen(port, host, () => {
|
2017-06-18 15:44:01 +00:00
|
|
|
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-19 23:15:57 +00:00
|
|
|
}).catch(this.nuxt.errorHandler)
|
2016-11-09 22:59:41 +00:00
|
|
|
}
|
|
|
|
|
2017-06-19 23:15:57 +00:00
|
|
|
close () {
|
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
this.server.close(err => {
|
|
|
|
if (err) {
|
|
|
|
return reject(err)
|
|
|
|
}
|
|
|
|
resolve()
|
|
|
|
})
|
|
|
|
})
|
2016-12-09 22:07:18 +00:00
|
|
|
}
|
2016-11-09 22:59:41 +00:00
|
|
|
}
|
|
|
|
|
2017-01-11 19:14:59 +00:00
|
|
|
export default Server
|