forked from CenterForDigitalHumanities/rerum_server_nodejs
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
70 lines (64 loc) · 1.87 KB
/
Copy pathindex.js
File metadata and controls
70 lines (64 loc) · 1.87 KB
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
import http from 'http'
import app from './app.js'
/**
* Express application instance used throughout the project. Exported
* primarily for testing or embedding inside another server.
*
* ```js
* import { app } from 'rerum_server'
* ```
*/
export { app }
/**
* Default export is the express app largely for backwards compatibility
* with consumers that do `import app from 'rerum_server'`.
*/
export default app
/**
* Helper that creates an HTTP server for the configured express app.
* The returned server is **not** listening yet; caller may attach
* additional listeners or configure timeouts before calling
* `server.listen(...)`.
*
* @param {number|string} [port=process.env.PORT??3001] port to assign to
* the express app and eventually listen on
* @returns {import('http').Server} http server instance
*/
export function createServer(port = process.env.PORT ?? 3001) {
app.set('port', port)
const server = http.createServer(app)
server.keepAliveTimeout = 8 * 1000
server.headersTimeout = 8.5 * 1000
return server
}
/**
* Convenience function to start the server immediately. Returns the
* server instance so callers can close it in tests or hook events.
*
* @param {number|string} [port] optional port override
* @returns {import('http').Server}
*/
export function start(port) {
const p = port ?? process.env.PORT ?? 3001
const server = createServer(p)
server.listen(p)
server.on('listening', () => {
console.log('LISTENING ON ' + p)
})
server.on('error', (error) => {
if (error.syscall !== 'listen') throw error
switch (error.code) {
case 'EACCES':
console.error(`Port ${p} requires elevated privileges`)
process.exit(1)
break
case 'EADDRINUSE':
console.error(`Port ${p} is already in use`)
process.exit(1)
break
default:
throw error
}
})
return server
}