CoolFace
Apppublic

Focus5555665/Chfh

sourceHugging Faceupdated 2y agoView on Hugging Face
0likes
server.js83 linesDownload Raw Back to root
1const express = require('express');2const http = require('http');3const socketIO = require('socket.io');4const fs = require('fs');5const path = require('path');6 7const app = express();8const server = http.createServer(app);9const io = socketIO(server);10 11app.use(express.static(path.join(__dirname, 'public')));12 13app.get('/', (req, res) => {14  res.sendFile(__dirname + '/index.html');15});16 17io.on('connection', (socket) => {18  socket.on('check-file', (chatId) => {19    const filePath = path.join(__dirname, 'chats', `${chatId}.txt`);20    fs.exists(filePath, (exists) => {21      if (exists) {22        fs.readFile(filePath, 'utf8', (err, data) => {23          if (err) {24            console.error('Error reading file:', err);25          } else {26            const messages = data.split('\n').filter((message) => message.trim() !== '');27            socket.emit('existing-messages', messages);28          }29        });30      }31      socket.emit('file-exists', exists);32    });33  });34 35  socket.on('create-file', (chatId) => {36    const filePath = path.join(__dirname, 'chats', `${chatId}.txt`);37    fs.writeFile(filePath, '', (err) => {38      if (err) {39        console.error('Error creating file:', err);40      } else {41        console.log('File created successfully');42      }43    });44  });45 46  socket.on('send-message', (data) => {47    const { chatId, message } = data;48    const filePath = path.join(__dirname, 'chats', `${chatId}.txt`);49    fs.appendFile(filePath, message + '\n', (err) => {50      if (err) {51        console.error('Error writing to file:', err);52      } else {53        io.emit('new-message', { chatId, message });54      }55    });56  });57 58  socket.on('delete-message', (data) => {59    const { chatId, index } = data;60    const filePath = path.join(__dirname, 'chats', `${chatId}.txt`);61    fs.readFile(filePath, 'utf8', (err, data) => {62      if (err) {63        console.error('Error reading file:', err);64      } else {65        const messages = data.split('\n');66        messages.splice(index, 1);67        const updatedContent = messages.join('\n');68        fs.writeFile(filePath, updatedContent, (err) => {69          if (err) {70            console.error('Error writing to file:', err);71          } else {72            io.emit('message-deleted', { chatId, index });73          }74        });75      }76    });77  });78});79 80const port = process.env.PORT || 3000;81server.listen(port, () => {82  console.log(`Server running on port ${port}`);83});