Whenever i try to run this code. All works fine, Writing is done correctly in the file as well, but everytime append runs, the page reloads for some reason…. any way to stop that reload? I have tried Using SetTimeout… But that just delays reloading. does not acutally stop the reload error…. This is my first question here as well. Any Help would be appreciated
//server side JS -----------------------------------
const http = require('http').createServer();
const fs = require('fs');
const io = require('socket.io')(http, {
cors: { origin : "*" }
});
io.on('connection', socket => {
console.log('A User Connected!');
socket.on('message', message => {
console.log(message);
let display = `${socket.id.substr(0,2)} Says: ${message}`;
io.emit('message', display);
display += 'n';
fs.appendFileSync('data.txt', display);
});
});
http.listen(8080, () => console.log('listening on http://localhost:8080 ') );
//Client-side Js -----------------------------------
const socket = io('ws://localhost:8080');
socket.on('message', text => {
const el = document.createElement('li');
el.innerHTML = text;
el.style.marginLeft = '500px';
document.querySelector('ul').append(el);
});
document.getElementById('btn').onclick = () => {
if(document.querySelector('input').value != ''){
const text = document.querySelector('input').value;
socket.emit('message', text);
document.querySelector('input').value = '';
}
}
document.addEventListener('keydown', (e) => {
if(e.key === 'Enter' && document.querySelector('input').value != ''){
const text = document.querySelector('input').value;
socket.emit('message', text);
document.querySelector('input').value = '';
}
});
<!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>Web Sockets Testings!</title>
<script src="https://cdn.socket.io/socket.io-3.0.0.js"></script>
<script defer src="app.js"></script>
</head>
<body>
<input placeholder="message!">
<button id="btn" onsubmit="return myFunction();">Send!</button>
<ul>
</ul>
</body>
</html>
ns, the page refreshes… Any Fixes..?