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