I'm fairly new to Nodejs and I'm building an app that ssh to a remote machine and get a tail -f of a log file.
The lines of the log file I'm receiving I'm sending to the client via socket-io (ver. 2.0.3)
Now I'm facing a problem that when a second browser tries to tail a different log, the new log is sent to both of the browsers instead of only the one who made the request.
I'm not sure if it's a problem with my socket-io code or the child_process.
Here's the server:
const express = require('express'),
app = express(),
path = require('path'),
bodyParser = require('body-parser'),
logger = require('morgan'),
server = require('http').Server(app),
io = require('socket.io')(server),
spawn = require('child_process').spawn,
events = require('events'),
eventEmitter = new events.EventEmitter();
// Fix body of requests
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
// Log the requests
app.use(logger('dev'));
// Serve static files
app.use(express.static(path.join(__dirname, '.')));
// Add a basic route – index page
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname, 'index.html'));
});
io.on('connection', (socket) => {
console.log(`client connected ${socket.client.id}`);
eventEmitter.on('tail', (data) => {
socket.tail = spawn('ssh', ['root#' + 'quality-p.company.com', 'tail -f', data.service], { shell: true });
socket.tail.stdout.on('data', (data) => {
console.log(`got new data ${data.toString()}`);
socket.emit('newLine', {line: data.toString().replace(/\n/g, '<br />')});
});
});
});
app.get('/tail', (req, res) => {
eventEmitter.emit('tail', req.query);
res.sendStatus(200);
});
// Bind to a port
server.listen(3005, () => {
console.log('running on localhost:' + 3005);
});
Client:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="./node_modules/socket.io-client/dist/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
$(() => {
let socket = io();
socket.on('connect', () => {
console.log('connected');
});
socket.on('newLine', (data) => {
console.log(`new data: ${data.line}`);
$("#tailing").append(data.line);
});
$('#tail').click(() => {
$.get('/tail', {
service: $('#service').val()
});
});
});
</script>
<title>Title</title>
</head>
<body>
<select id="service">
<option id="tnet" value="/var/log/tnet">tnet</option>
<option id="consul" value="/var/log/consul">consul</option>
</select>
<button id="tail">tail</button>
<div id="tailing" style="background-color: antiquewhite;">
</div>
</body>
</html>
Server
const express = require('express'),
app = express(),
path = require('path'),
bodyParser = require('body-parser'),
logger = require('morgan'),
server = require('http').Server(app),
io = require('socket.io')(server),
spawn = require('child_process').spawn;
// Fix body of requests
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
// Log the requests
app.use(logger('dev'));
// Serve static files
app.use(express.static(path.join(__dirname, '.')));
// Add a basic route – index page
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname, 'index.html'));
});
var tails = {};
io.on('connection', (socket) => {
console.log(`client connected ${socket.client.id}`);
socket.on('tail', (data) => {
socket.join(data.service);
if (typeof tails[data.service] == "undefined") {
tails[data.service] = spawn('ssh', ['root#' + 'quality-p.company.com', 'tail -f', data.service], {
shell: true
});
tails[data.service].stdout.on('data', (data) => {
console.log(`got new data ${data.toString()}`);
io.to(data.service).emit('newLine', {
line: data.toString().replace(/\n/g, '<br />')
});
});
}
});
});
// Bind to a port
server.listen(3005, () => {
console.log('running on localhost:' + 3005);
});
Client
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="./node_modules/socket.io-client/dist/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
$(() => {
let socket = io();
socket.on('connect', () => {
console.log('connected');
});
socket.on('newLine', (data) => {
console.log(`new data: ${data.line}`);
$("#tailing").append(data.line);
});
$('#tail').click(() => {
socket.emit('tail', {
service: $('#service').val()
});
});
});
</script>
<title>Title</title>
</head>
<body>
<select id="service">
<option id="tnet" value="/var/log/tnet">tnet</option>
<option id="consul" value="/var/log/consul">consul</option>
</select>
<button id="tail">tail</button>
<div id="tailing" style="background-color: antiquewhite;">
</div>
</body>
</html>
Related
I'm having a go with the socket.io https://socket.io/get-started/chat, but my problem is that when i send message then the message cant automatically into chat box. i need to reload the page to view the chat that i sent. So how to make the chat automatically insert to chat box?. i already implement into my project. i already used socket.emit as you can see at then html file. is there the right way to put it?
server.js
var express = require('express');
var env = require('dotenv').config()
var ejs = require('ejs');
var path = require('path');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var session = require('express-session');
const MongoDBStore = require('connect-mongodb-session')(session)
const cookieParser = require('cookie-parser')
var http = require('http').Server(app);
var io = require('socket.io')(http);
var cors = require('cors')
app.use(cors())
app.use(cookieParser());
// mongodb://localhost:27017 127.0.0.1:27017
mongoose.set('strictQuery', true);
mongoose.connect('mongodb://127.0.0.1:27017/findaprofessional', {
useNewUrlParser: true,
useUnifiedTopology: true
}, (err) => {
if (!err) {
console.log('MongoDB Connection Succeeded.');
} else {
console.log('Error in DB connection : ' + err);
}
});
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
});
const oneDay = 1000 * 60 * 60 * 24;
app.use(session({
secret: 'work hard',
saveUninitialized:true,
cookie: { maxAge: oneDay },
resave: true
}));
// ni lain
app.set("view engine", "ejs")
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use('/css', express.static(path.resolve(__dirname, "asset/css")))
app.use('/img', express.static(path.resolve(__dirname, "asset/img")))
app.use('/js', express.static(path.resolve(__dirname, "asset/js")))
app.use('/vendor', express.static(path.resolve(__dirname, "asset/vendor")))
app.use('/lib', express.static(path.resolve(__dirname, "asset/lib")))
app.use('/scss', express.static(path.resolve(__dirname, "asset/scss")))
app.use('/pic', express.static(path.resolve(__dirname, "asset/img/pic")))
var index = require('./routes/index');
const { Socket } = require('socket.io');
app.use('/', index);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
var err = new Error('File Not Found');
err.status = 404;
next(err);
});
// error handler
// define as the last app.use callback
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.send(err.message);
});
io.on('connection', () =>{
console.log('a user is connected')
io.on("disconnect", function () {
console.log("user disconnected");
});
})
var server = http.listen(3000, () => {
console.log('Server is started on http://127.0.0.1:'+ server.address().port);
});
routing
// user chat
var http = require('http').Server(router);
var io = require('socket.io')(http);
// Render Message
router.get('/messages/:id', async function (req, res, next) {
user = await User.findOne({_id: req.session.userId}, {username: 1})
return res.render("user/messages.ejs", {user: user, booking: req.params.id});
});
// Display Message from DB
router.get('/messageslist/:booking', (req, res) => {
Message.find({booking: req.params.booking})
.populate({
path: "pro",
model: Pro,
}).populate({
path: "user",
model: User,
}).exec().then((data) => {
res.json(data)
})
})
router.get('/messages', (req, res) => {
Message.find({}, (err, messages) => {
res.send(messages);
})
})
router.post('/messages', async (req, res) => {
const {booking, user, message} = req.body
try {
var msg = new Message({
booking: booking,
message: message,
user: user
});
var savedMessage = await msg.save()
console.log('saved');
var censored = await Message.findOne({
message: 'badword'
});
if (censored)
await Message.remove({
_id: censored.id
})
else
io.emit('message', req.body);
res.sendStatus(200);
} catch (error) {
res.sendStatus(500);
return console.log('error', error);
} finally {
console.log('Message Posted')
}
})
HTML
<!DOCTYPE html>
<html lang="en">
<%- include("../header.ejs") %>
<head>
<link href="/css/sb-admin-2.min.css" rel="stylesheet">
<link href="/css/chat.css" rel="stylesheet">
<script src="https://code.jquery.com/jquery-3.2.1.min.js" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js"
integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous">
</script>
</script>
<script src="/socket.io/socket.io.js"></script>
</head>
</head>
<!-- start here! -->
<section class="msger" style="margin: auto;">
<header class="msger-header">
<div class="msger-header-title">
<i class="fas fa-comment-alt"></i> Chat
</div>
<div class="msger-header-options">
<span><i class="fas fa-cog"></i></span>
</div>
</header>
<main class="msger-chat">
</main>
<form class="msger-inputarea">
<input type="hidden" name="booking" value="<%= booking %>">
<input type="hidden" id="name" class="form-control" readonly placeholder="Name"
value="<%= user.username %>">
<input type="text" name="user" value="<%= user._id %>">
<input id="message" type="text" class="msger-input" placeholder="Enter your message...">
<button id="send" type="submit" class="msger-send-btn">Send</button>
</form>
</section>
<!-- End of Main Content -->
</div>
<!-- End of Content Wrapper -->
</div>
<!-- End of Page Wrapper -->
<!-- Scroll to Top Button-->
<a class="scroll-to-top rounded" href="#page-top">
<i class="fas fa-angle-up"></i>
</a>
</div>
<!-- End of Main Content -->
</div>
<!-- End of Content Wrapper -->
</div>
<!-- End of Page Wrapper -->
<!-- Bootstrap core JavaScript-->
<script src="/vendor/jquery/jquery.min.js"></script>
<script src="/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<!-- Core plugin JavaScript-->
<script src="/vendor/jquery-easing/jquery.easing.min.js"></script>
<!-- Custom scripts for all pages-->
<script src="/js/sb-admin-2.min.js"></script>
<!-- Page level plugins -->
<script src="/vendor/datatables/jquery.dataTables.min.js"></script>
<script src="/vendor/datatables/dataTables.bootstrap4.min.js"></script>
<!-- Page level custom scripts -->
<script src="/js/demo/datatables-demo.js"></script>
<script type="text/javascript" src="/js/mdb.min.js"></script>
<!-- Custom scripts -->
<script>
var socket = io();
$(() => {
$("#send").click(() => {
sendMessage({
booking: $("input[name=booking]").val(),
user: $("input[name=user]").val(),
message: $("#message").val()
});
})
getMessages()
})
socket.on('message', addMessages)
socket.on('message', getMessages)
socket.emit('message', getMessages)
socket.emit('message', addMessages)
function addMessages(message) {
if(message.user && message.user != '') {
if($("input[name=user]").val() == message.user._id) {
html = '<div class="msg right-msg"><div class="msg-img" style="background-image: url('+message.user.image +')"></div>'
html += '<div class="msg-bubble"><div class="msg-info"><div class="msg-info-name">' + message.user.username + '</div><div class="msg-info-time">' + message.createdAt + '</div></div>'
}
}
else {
html = '<div class="msg left-msg"><div class="msg-img" style="background-image: url('+message.pro.image +')"></div>'
html += '<div class="msg-bubble"><div class="msg-info"><div class="msg-info-name">' + message.pro.username + '</div><div class="msg-info-time">' + message.createdAt + '</div></div>'
}
html += '<div class="msg-text">' + message.message + '</div></div></div>'
$(".msger-chat").append(html)
}
function getMessages() {
$.get('http://localhost:3000/messageslist/<%=booking%>', (data) => {
data.forEach(addMessages);
})
}
function sendMessage(message) {
$.post('http://localhost:3000/messages', message)
}
</script>
i tried to automatically get the message without reload the page but it doenst work. Can anyone see where the problem is?
From what I know, the default behavior when you click a button with type submit inside a form, it tries to reload the page even though you haven't defined any function or other page for it to go.
You would have to get the submit event from the form and use the preventDefault() funciton for this event, check out this thread for more info:
JavaScript code to stop form submission
So you would stop the form submission and then get new messages for the page, executing the javascript to add the new messages to the page by manipulating the DOM.
You can write socker.write() method for accessing real time messages in nodejs.
So I'm trying to host a web app using node.js express and my server.js seems to hang upon using npm start. In my package.json file it calls node server.js and everything starts properly but my website won't deploy to the local host for me to view. I have a feeling it is either something to do with the location of my css/index.html or it could be something with the way i create the request from the client side from index.html I'm new to backend, so really out in the deep on this one.
//1.) create http server
const PORT = process.env.PORT || 2525;
const INDEX = '/public/index.html';
const express = require('express')
var server = express();
console.log(__dirname)
server.use(express.static(__dirname + "/public"));
server.get('public/index.html', function(req, res, next) {
res.sendFile(__dirname + INDEX);
});
server.listen(PORT);
//2.) Create a websocket server
const { Server } = require('ws');
const wss = new Server({ server });
//3.) Handle connections
wss.on('connection', (ws) => {
console.log('Client connected');
ws.on('close', () => console.log('Client disconnected'));
});
//4.) Boradcast updates
setInterval(() => {
wss.clients.forEach((client) => {
client.send(new Date().toTimeString());
});
}, 1000);
console.log('Server started at http://localhost:' + PORT);
This is my index.html below
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name='viewport' content='width=device-width, initial-scale=1'>
<title>am i sheep</title>
<link rel="stylesheet" href="css/style.css" type="text/css">
</head>
<body>
<div>
<span>
<h3> Am I Sheep<h3>
</span>
</div>
<div>
</div>
<div>
<input type="file" id="fileID" hidden></input>
<label for='fileID'>select image</label>
</div>
<div>
<h1 id='server-time'>current time</h1>
<script>
var HOST = location.origin.replace(/^http/, 'ws')
var ws = new WebSocket(HOST);
var el;
ws.onmessage = function (event) {
el = document.getElementById('server-time');
el.innerHTML = 'Server time: ' + event.data;
};
</script>
</div>
</body>
</html>
UPDATE:
So the issue that seems to be popping up now is
WebSocket connection to 'ws://localhost:2525/' failed
var ws = new WebSocket(HOST);
So the error is happening between the handshake between the client and server
The server.js
//1.) create http server
const PORT = process.env.PORT || 2525;
const INDEX = "/public/index.html";
const express = require("express");
const { createServer } = require("http");
const app = express();
const httpServer = createServer(app);
// Static files
app.use(express.static(__dirname + "/public"));
app.get("/", function (req, res, next) {
res.sendFile(__dirname + INDEX);
});
//2.) Create a websocket server
const { Server } = require("ws");
const wss = new Server({ server: httpServer });
//3.) Handle connections
wss.on("connection", ws => {
console.log("Client connected");
ws.on("close", () => console.log("Client disconnected"));
});
//4.) Boradcast updates
setInterval(() => {
wss.clients.forEach(client => {
client.send(new Date().toTimeString());
});
}, 1000);
httpServer.listen(PORT, () => console.log("Server started at http://localhost:" + PORT));
The index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name='viewport' content='width=device-width, initial-scale=1'>
<title>am i sheep</title>
<link rel="stylesheet" href="css/style.css" type="text/css">
</head>
<body>
<div>
<span>
<h3> Am I Sheep<h3>
</span>
</div>
<div>
</div>
<div>
<input type="file" id="fileID" hidden></input>
<label for='fileID'>select image</label>
</div>
<div>
<h1 id='server-time'>current time</h1>
<script>
var HOST = location.origin.replace(/^http/, 'ws')
var ws = new WebSocket(HOST);
var el;
ws.onopen = function () {
alert('Connection Open');
};
ws.onerror = function (error) {
alert('Error');
};
ws.onmessage = function (event) {
el = document.getElementById('server-time');
el.innerHTML = 'Server time: ' + event.data;
};
</script>
</div>
</body>
</html>
I'm learning the socket.io library in Node.js and I can't make the server receive data, only send. During tests I noticed that the io.on listener function isn't even being called, and I don't know where's my mistake. What exactly works and what doesn't is marked with commentaries in the code bellow.
My server-side code:
"use strict";
const http = require("http");
const express = require("express");
const { Server } = require("socket.io");
const { log } = console;
const app = express();
const server = http.createServer(app);
const io = new Server(server);
app.use(express.urlencoded({extended: false}));
app.use(express.json());
app.use(express.static(__dirname + "/public"));
io.on("connect", socket => {
const { id } = socket;
io.emit("receiveMsg", id); // This works
})
io.on("sendMsg", msg => { // This doesn't work
log("sendMsg: " + msg);
});
server.listen(8080);
My client-side code:
const socket = io();
const { log } = console;
socket.on("receiveMsg", msg => { // This works
log("receiveMsg: " + msg);
});
const sendMsg = () => {
const msg = document.querySelector("#msg").value;
socket.emit("sendMsg", msg); // This doesn't work
}
My client-side HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Test</title>
</head>
<body>
<h1>Hello, world!</h1>
<input type="text" id="msg" placeholder="msg">
<button onclick="sendMsg()">send</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.1.3/socket.io.js"></script>
<script>
// Client-side code here
</script>
</body>
</html>
based on the doc https://socket.io/docs/v4/client-socket-instance/
the connection event is connection on server side, and connect on client side
// server-side
io.on("connection", (socket) => {
console.log(socket.id); // x8WIv7-mJelg7on_ALbx
});
// client-side
socket.on("connect", () => {
console.log(socket.id); // x8WIv7-mJelg7on_ALbx
});
for Emit events, if you see here https://socket.io/docs/v4/emitting-events/
it seems requires us to put the subscription event inside connection block
// server-side
io.on("connection", (socket) => {
socket.on("hello", (arg) => {
console.log(arg); // world
});
});
// client-side
socket.emit("hello", "world");
so maybe you can try to change your server code
io.on("connection", (socket) => {
socket.on("sendMsg", msg => { // This doesn't work
log("sendMsg: " + msg);
}
});
it uses socket.on, not io.on on server side
I'm trying to build a database using mongodb where it will render to an html page using ejs. Backend is node/express.
How do I link the button to an addeventlistener. EJS documentation is limited and I've read other posts that says ejs only renders html but no other functionality.
Eventually, I would like to use an async/await to link the js with the backend.
Here is my ejs:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<h1>The Beautiful Game</h1>
<form action="/players" method="POST">
<input type="text" placeholder="name" name="name" />
<input type="text" placeholder="club" name="club" />
<button type="submit" class='submitButton'>Submit</button>
</form>
<h2>Players</h2>
<ul class="players">
<% for (var i = 0; i < players.length; i++) {%>
<li class="players">
<span><%= players[i].name %></span>:
<span><%= players[i].club %></span>
<button class="dataDeleteNameButton" data-id="<%=players[i]._id%>">Delete</button> <!-- linking this button -->
</li>
<% } %>
</ul>
<script type="text/javascript" src="js/main.js"></script>
</body>
</html>
Here is my js:
document
.querySelector("dataDeleteNameButton")
.addEventListener("click", deleteEntry);
async function deleteEntry() {
console.log("Button is working!");
}
Here is the server, if needed:
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
const cors = require("cors");
const MongoClient = require("mongodb").MongoClient;
const PORT = process.env.PORT || 8000;
app.use(cors());
const username = "hidden";
const password = "hidden";
const connectionString = `mongodb+srv://${username}:${password}#cluster0.7k2ww.mongodb.net/myFirstDatabase?retryWrites=true&w=majority`;
MongoClient.connect(connectionString, { useUnifiedTopology: true })
.then((client) => {
console.log("Connected to database");
const db = client.db("soccer-players");
const playerCollection = db.collection("players");
app.set("view engine", "ejs");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(express.static("public"));
app.get("/", (req, res) => {
db.collection("players")
.find()
.toArray()
.then((result) => {
res.render("index.ejs", { players: result });
})
.catch((error) => console.error(error));
});
app.get("/api/players", (req, res) => {
db.collection("players")
.find()
.toArray((err, arr) => {
res.json(arr);
});
});
app.post("/players", (req, res) => {
playerCollection
.insertOne(req.body)
.then((result) => {
res.redirect("/");
})
.catch((error) => console.error(error));
console.log(req.body);
});
app.delete("/", (req, res) => {
// playerCollection.deleteOne() <--
// let findID =
});
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
})
.catch((error) => console.error(error));
Picture of what it looks like:
This is my script tag path: ../client-side-folder/js-folder/main.js
Directory:
main-folder
+--client-side-folder
+----js-folder
+------main.js
+--views-folder
+----index.ejs
You can just do onclick="myFunction(theIdOfTheButtonHere)"
Here is an example:
https://www.w3schools.com/jsref/event_onclick.asp
When a user clicks an html button (#new) I want to store their socket.id into an array (userQueue) on my node server but I'm having trouble figuring out how to do this. Do I need to set up a post request or is there a way through socket.io?
App.js (Server):
// App setup
var express = require('express'),
socket = require('socket.io'),
app = express(),
bodyParser = require("body-parser");
var server = app.listen(3000, function() {
console.log('listening to requests on port 3000');
});
var io = socket(server);
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static('public'));
// Room Logic
var userQueue = [];
io.on('connection', function(socket) {
console.log('made socket connection', socket.id);
socket.on('chat', function(data) {
io.sockets.emit('chat', data);
});
socket.on('typing', function(data) {
socket.broadcast.emit('typing', data);
});
});
Chat.js (client side):
// Make connection
var socket = io.connect('http://localhost:3000');
// Query DOM
var message = document.getElementById('message');
handle = document.getElementById('handle'),
btn = document.getElementById('send'),
btnNew = document.getElementById('new'),
output = document.getElementById('output'),
feedback = document.getElementById('feedback');
// Emit events
btn.addEventListener('click', function(){
socket.emit('chat', {
message: message.value,
handle: handle.value
});
});
message.addEventListener('keypress', function() {
socket.emit('typing', handle.value);
});
// Listen for events
socket.on('chat', function(data) {
feedback.innerHTML = ""
output.innerHTML += '<p><strong>' + data.handle + ':</strong>' + data.message + '</p>'
});
// Emit 'is typing'
socket.on('typing', function(data) {
feedback.innerHTML = '<p><em>' + data + ' is typing a message...</em></p>'
});
Index.html:
<!DOCTYPE html>
<html>
<head>
<title>WebSockets 101</title>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js"></script>
<link rel="stylesheet" type="text/css" href="/styles.css">
</head>
<body>
<div id="mario chat">
<div id="chat-window">
<div id="output"></div>
<div id="feedback"></div>
</div>
<input id="handle" type="text" placeholder="Handle">
<input id="message" type="text" placeholder="Message">
<button id="send">Send</button>
<button id="new">New</button>
</div>
<script type="text/javascript" src="/chat.js"></script>
</body>
</html>
I believe that a post request will probably work as well, but if you want to simply work with socket.io you can consider doing something similar to your chat event by adding this in your chat.js:
btnNew.addEventListener('click', function() {
socket.emit('new user', socket.id);
});
And on the server side, app.js:
socket.on('new user', function(id) {
userQueue.push(id);
});
And it should be stored in the array. Hope this helps!