-
Notifications
You must be signed in to change notification settings - Fork 21
/
nodeico.js
127 lines (101 loc) · 2.8 KB
/
nodeico.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
'use strict'
const path = require('path')
, fs = require('fs')
, http = require('http')
, swig = require('swig')
, humanize = require('humanize-number')
, Router = require('routes-router')
, bole = require('bole')
, sendPlain = require('send-data/plain')
, sendError = require('send-data/error')
, st = require('st')
, uuid = require('node-uuid')
, log = bole('server')
, reqLog = bole('server:request')
, isDev = (/^dev/i).test(process.env.NODE_ENV)
, port = process.env.PORT || 3000
, start = new Date()
, routes = [
require('./lib/routes/index')
, require('./lib/routes/script')
, require('./lib/routes/npm-badge')
, require('./lib/routes/npm-downloads-badge')
, require('./lib/routes/user')
, require('./lib/routes/npm-api-info-passthrough')
, require('./lib/routes/npm-pkg') // last
]
bole.output({
level : isDev ? 'debug' : 'info',
stream : process.stdout
})
if (process.env.LOG_FILE) {
console.log(`Starting logging to ${process.env.LOG_FILE}`)
bole.output({
level : 'debug',
stream : fs.createWriteStream(process.env.LOG_FILE)
})
}
if (process.env.NODE_TITLE)
process.title = process.env.NODE_TITLE
swig.setDefaults({
root : path.join(__dirname, 'views')
, cache : isDev ? false : 'memory'
})
swig.setFilter('humanize', humanize)
const mount = st({
path : path.join(__dirname, './public')
, url : '/'
, index : false
, cache : isDev ? false : {}
})
const router = Router({
errorHandler: (req, res, err) => {
req.log.error(err)
sendError(req, res, { body: err })
}
, notFound: (req, res) => {
if (mount(req, res))
return
sendPlain(req, res, {
body: 'Not found: ' + req.url
, statusCode: 404
})
}
})
routes.forEach((route) => {
if (!Array.isArray(route.path))
return router.addRoute(route.path, route)
route.path.forEach(function (path) {
router.addRoute(path, route)
})
})
function handler (req, res) {
if (req.url == '/_status')
return sendPlain(req, res, 'OK')
// unique logger for each request
req.log = reqLog(uuid.v4())
req.log.info(req)
res.setHeader('x-startup', start)
res.setHeader('x-powered-by', 'whatevs')
router(req, res)
}
module.exports = function () {
return http.createServer(handler)
.on('error', (err) => {
log.error(err)
throw err
})
}
if (require.main === module) {
module.exports().listen(port, (err) => {
if (err) {
log.error(err)
throw err
}
log.info(`Server started on port ${port}`)
console.log()
console.log(`>> Running: http://localhost:${port}`)
console.log()
})
}
//*/