-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
93 lines (81 loc) · 2.5 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
process.SERVER_BUILD = true
const Koa = require("koa")
const Nuxt = require("nuxt").Nuxt
const Builder = require("nuxt").Builder
const koaRouter = require("koa-router")()
const config = require("./nuxt.config.js")
const router = require("./routes/index")
const mount = require("koa-mount")
const serve = require("koa-static")
const compress = require("koa-compress")
const http = require("http")
const path = require("path")
const staticCache = require("./plugins/staticCache")
require("./plugins/logger")
const app = new Koa()
config.dev = !(app.env === "production")
const isApiDev = app.env === "api-dev"
const isPm2Dev = app.env === "pm2-dev"
if(isApiDev || isPm2Dev){
//强制false
config.dev = false
}
const nuxt = new Nuxt(config)
// Build only in dev mode
if (config.dev) {
// logger
app.use(async function (ctx, next) {
const start = new Date()
await next()
const ms = new Date() - start
console.info(`koa:render ${ctx.method} ${ctx.url} - ${ms}ms`)
});
if(!isApiDev && !isPm2Dev){
//API调试模式下,不build
const builder = new Builder(nuxt)
builder.build().catch((error) => {
console.error(error) // eslint-disable-line no-console
process.exit(1)
})
}
}
//http路由
router(koaRouter, app)
app.use(koaRouter.routes())
//缓存
if (!config.dev) {
//gzip
app.use(compress({
filter: function (content_type) {
return /js|css|jpe?g|png|gif|apk|svg/i.test(content_type)
},
threshold: 2048,
flush: require("zlib").Z_SYNC_FLUSH
}))
//cdn回源
app.use(mount("/static",serve("./.nuxt/dist",{maxage:24 * 60 * 60 * 7 * 1000, gzip:true})))
app.use(staticCache(path.join(__dirname, "static"), {
maxAge: 24 * 60 * 60 * 7,
filter:["js","css","jpg","png","apk","svg"]
}))
}
app.use(async function (ctx, next) {
ctx.status = 200 // koa defaults to 404 when it sees that status is unset
return new Promise((resolve, reject) => {
ctx.res.on('close', resolve)
ctx.res.on('finish', resolve)
nuxt.render(ctx.req, ctx.res, promise => {
// nuxt.render passes a rejected promise into callback on error.
promise.then(resolve).catch(reject)
})
})
})
//for graceful reload
// process.on('SIGINT', function() {
// db.stop(function(err) {
// process.exit(err ? 1 : 0);
// });
// });
app.listen(3000, "0.0.0.0", ()=>{
console.info( `Server listening on 0.0.0.0:3000` )
})