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