Skip to content

Instantly share code, notes, and snippets.

@ShaunSHamilton
Last active October 17, 2022 13:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ShaunSHamilton/cd93e8dcac03c86fd490d480ed69e994 to your computer and use it in GitHub Desktop.
Save ShaunSHamilton/cd93e8dcac03c86fd490d480ed69e994 to your computer and use it in GitHub Desktop.
Advanced Node and Express - Communicate by Emitting
$(document).ready(function () {
/*global io*/
let socket = io();
socket.on('user count', function (data) {
console.log(data);
});
// Form submittion with new message in field with id 'm'
$('form').submit(function () {
var messageToSend = $('#m').val();
$('#m').val('');
return false; // prevent form submit from refreshing page
});
});
'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.js');
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');
app.set('views', './views/pug');
app.use(session({
secret: process.env.SESSION_SECRET,
resave: true,
saveUninitialized: true,
cookie: { secure: false }
}));
app.use(passport.initialize());
app.use(passport.session());
fccTesting(app); // For fCC testing purposes
app.use('/public', express.static(process.cwd() + '/public'));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
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');
});
}).catch(e => {
app.route('/').get((req, res) => {
res.render('index', { title: e, message: 'Unable to connect to database' });
});
});
const PORT = process.env.PORT || 3000;
http.listen(PORT, () => {
console.log(`Listening on port ${PORT}`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment