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