Here is a sample code for a todo app using Node.js, socket.io, and MySQL:
const express = require('express');
const app = express();
const http = require('http').createServer(app);
const io = require('socket.io')(http);
const mysql = require('mysql');
// replace with your MySQL credentials
const connection = mysql.createConnection({
host: 'localhost',
user: 'username',
password: 'password',
database: 'todos'
});
connection.connect();
app.use(express.static('public'));
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
io.on('connection', (socket) => {
console.log('a user connected');
socket.on('disconnect', () => {
console.log('user disconnected');
});
socket.on('add todo', (todo) => {
connection.query('INSERT INTO todos (todo) VALUES (?)', [todo], (error) => {
if (error) throw error;
console.log('todo added: ', todo);
io.emit('todo added', todo);
});
});
socket.on('delete todo', (id) => {
connection.query('DELETE FROM todos WHERE id = ?', [id], (error) => {
if (error) throw error;
console.log('todo deleted: ', id);
io.emit('todo deleted', id);
});
});
});
http.listen(3000, () => {
console.log('listening on *:3000');
});
This code uses the following libraries:
- express: a web framework for Node.js
- socket.io: a library for real-time communication between client and server
- mysql: a library for connecting to and querying a MySQL database
The code sets up a server using express and socket.io, and listens for connection and disconnection events from clients. It also listens for events to add or delete todos, and sends updates to all connected clients when these events occur.
To set up the MySQL database, you will need to create a database and a table for the todos. You can do this by running the following SQL commands:
CREATE DATABASE todos;
USE todos;
CREATE TABLE todos (
id INT AUTO_INCREMENT PRIMARY KEY,
todo VARCHAR(255) NOT NULL
);
This will create a database called “todos” with a table called “todos” that has two columns: “id” and “todo”. The “id” column is an auto-incrementing primary key, and the “todo” column is a string that cannot be null.
To run the todo app, make sure you have Node.js and MySQL installed, and then start the server by running the following command:
node server.js
You should see a message indicating that the server is listening on port 3000. You can then visit the app in your web browser by going to http://localhost:3000.
Generated from ChatGPT of openai.com