-
-
Save camperbot/ab1007b76069884fb45b215d3c4496fa to your computer and use it in GitHub Desktop.
Advanced Node and Express - Handle a Disconnect
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
require('dotenv').config(); | |
const express = require('express'); | |
const myDB = require('./connection'); | |
const fccTesting = require('./freeCodeCamp/fcctesting.js'); | |
const session = require('express-session'); | |
const passport = require('passport'); | |
const routes = require('./routes'); | |
const auth = require('./auth.js'); | |
const app = express(); | |
const http = require('http').createServer(app); | |
const io = require('socket.io')(http); | |
app.set('view engine', 'pug'); | |
fccTesting(app); // For fCC testing purposes | |
app.use('/public', express.static(process.cwd() + '/public')); | |
app.use(express.json()); | |
app.use(express.urlencoded({ extended: true })); | |
app.use(session({ | |
secret: process.env.SESSION_SECRET, | |
resave: true, | |
saveUninitialized: true, | |
cookie: { secure: false }, | |
})); | |
app.use(passport.initialize()); | |
app.use(passport.session()); | |
myDB(async (client) => { | |
const myDataBase = await client.db('database').collection('users'); | |
routes(app, myDataBase); | |
auth(app, myDataBase); | |
let currentUsers = 0; | |
io.on('connection', (socket) => { | |
++currentUsers; | |
io.emit('user count', currentUsers); | |
console.log('A user has connected'); | |
socket.on('disconnect', () => { | |
console.log('A user has disconnected'); | |
--currentUsers; | |
io.emit('user count', currentUsers); | |
}); | |
}); | |
}).catch((e) => { | |
app.route('/').get((req, res) => { | |
res.render('pug', { title: e, message: 'Unable to login' }); | |
}); | |
}); | |
http.listen(process.env.PORT || 3000, () => { | |
console.log('Listening on port ' + process.env.PORT); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment