Add 2 downgrades (duplicated) to avoid dev warnings
[vchess.git] / server / bin / www
CommitLineData
1d184b4c
BA
1#!/usr/bin/env node
2
3/**
4 * Module dependencies.
5 */
6
c5c47010
BA
7let app = require('../app');
8const debug = require('debug')('vc:server');
9const http = require('http');
1d184b4c
BA
10
11/**
12 * Get port from environment and store in Express.
13 */
14
c5c47010 15const port = normalizePort(process.env.PORT || '3000');
1d184b4c
BA
16app.set('port', port);
17
18/**
19 * Create HTTP server.
20 */
21
c5c47010 22let server = http.createServer(app);
1d184b4c 23
d431028c
BA
24/*
25 * CRON tasks
26 */
27
c5c47010
BA
28let cron = require('node-cron');
29const UserModel = require("../models/User");
30const GameModel = require("../models/Game");
d431028c 31cron.schedule('0 0 0 * * *', function() {
fd41e587 32 // Remove unlogged users and unstarted games every 24h
dac39588 33 UserModel.cleanUsersDb();
1b99d981 34 GameModel.cleanGamesDb();
d431028c
BA
35});
36
1d184b4c
BA
37/**
38 * Listen on provided port, on all network interfaces.
39 */
40
41server.listen(port);
42server.on('error', onError);
43server.on('listening', onListening);
44
45/*
46 * Sockets handling
47 */
48
49const WebSocket = require('ws');
50const wss = new WebSocket.Server({ server: server });
51require('../sockets')(wss);
52
53/**
54 * Normalize a port into a number, string, or false.
55 */
56
57function normalizePort(val) {
c5c47010 58 const parsedPort = parseInt(val, 10);
1d184b4c 59
c5c47010 60 if (isNaN(parsedPort)) {
1d184b4c
BA
61 // named pipe
62 return val;
63 }
64
c5c47010 65 if (parsedPort >= 0) {
1d184b4c 66 // port number
c5c47010 67 return parsedPort;
1d184b4c
BA
68 }
69
70 return false;
71}
72
73/**
74 * Event listener for HTTP server "error" event.
75 */
76
77function onError(error) {
78 if (error.syscall !== 'listen') {
79 throw error;
80 }
81
c5c47010 82 const bind = typeof port === 'string'
1d184b4c
BA
83 ? 'Pipe ' + port
84 : 'Port ' + port;
85
86 // handle specific listen errors with friendly messages
87 switch (error.code) {
88 case 'EACCES':
89 console.error(bind + ' requires elevated privileges');
90 process.exit(1);
91 break;
92 case 'EADDRINUSE':
93 console.error(bind + ' is already in use');
94 process.exit(1);
95 break;
96 default:
97 throw error;
98 }
99}
100
101/**
102 * Event listener for HTTP server "listening" event.
103 */
104
105function onListening() {
c5c47010
BA
106 const addr = server.address();
107 const bind = typeof addr === 'string'
1d184b4c
BA
108 ? 'pipe ' + addr
109 : 'port ' + addr.port;
110 debug('Listening on ' + bind);
111}