2016-11-07 01:34:58 +00:00
|
|
|
#!/usr/bin/env node --harmony_proxies
|
|
|
|
|
|
|
|
const http = require('http')
|
2016-11-07 19:57:44 +00:00
|
|
|
const co = require('co')
|
2016-11-07 01:34:58 +00:00
|
|
|
const fs = require('fs')
|
2016-11-07 19:57:44 +00:00
|
|
|
const pify = require('pify')
|
2016-11-07 01:34:58 +00:00
|
|
|
const serveStatic = require('serve-static')
|
|
|
|
const Nuxt = require('../')
|
|
|
|
const { resolve } = require('path')
|
|
|
|
|
|
|
|
const rootDir = resolve(process.argv.slice(2)[0] || '.')
|
|
|
|
const nuxtConfigFile = resolve(rootDir, 'nuxt.config.js')
|
|
|
|
let options = {}
|
|
|
|
if (fs.existsSync(nuxtConfigFile)) {
|
|
|
|
options = require(nuxtConfigFile)
|
|
|
|
}
|
|
|
|
if (typeof options.rootDir !== 'string') {
|
|
|
|
options.rootDir = rootDir
|
|
|
|
}
|
|
|
|
|
|
|
|
new Nuxt(options)
|
|
|
|
.then((nuxt) => {
|
|
|
|
new Server(nuxt)
|
|
|
|
.listen(process.env.PORT, process.env.HOST)
|
|
|
|
})
|
|
|
|
.catch((err) => {
|
|
|
|
console.error(err)
|
|
|
|
process.exit()
|
|
|
|
})
|
|
|
|
|
|
|
|
class Server {
|
|
|
|
|
|
|
|
constructor (nuxt) {
|
|
|
|
this.server = http.createServer(this.handle.bind(this))
|
2016-11-07 19:57:44 +00:00
|
|
|
this.serveStatic = pify(serveStatic(resolve(rootDir, 'static')))
|
2016-11-07 01:34:58 +00:00
|
|
|
this.nuxt = nuxt
|
|
|
|
return this
|
|
|
|
}
|
|
|
|
|
|
|
|
handle (req, res) {
|
|
|
|
const method = req.method.toUpperCase()
|
2016-11-07 19:57:44 +00:00
|
|
|
const self = this
|
2016-11-07 01:34:58 +00:00
|
|
|
|
|
|
|
if (method !== 'GET' && method !== 'HEAD') {
|
|
|
|
return this.nuxt.render(req, res)
|
|
|
|
}
|
2016-11-07 19:57:44 +00:00
|
|
|
co(function * () {
|
|
|
|
if (req.url.includes('/static/')) {
|
|
|
|
const url = req.url
|
|
|
|
req.url = req.url.replace('/static/', '/')
|
|
|
|
yield self.serveStatic(req, res)
|
|
|
|
req.url = url
|
|
|
|
}
|
|
|
|
})
|
|
|
|
.then(() => {
|
2016-11-07 01:34:58 +00:00
|
|
|
// File not found
|
|
|
|
this.nuxt.render(req, res)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
listen (port, host) {
|
|
|
|
host = host || 'localhost'
|
|
|
|
port = port || 3000
|
|
|
|
this.server.listen(port, host, () => {
|
|
|
|
console.log('Ready on http://%s:%s', host, port)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|