UNPKG

nodly

Version:

Nodly is an interactive CLI for scaffolding modern Node.js/Express.js backend projects with instant setup for databases, mailers, queues, sockets, and more. Skip boilerplate and start building features fast.

38 lines (30 loc) 732 B
import { Server } from "socket.io"; let io; export const initSocketIO = (server) => { io = new Server(server, { cors: { origin: "*", methods: ["GET", "POST"], }, }); io.on("connection", (socket) => { console.log(`New client connected: ${socket.id}`); socket.on("disconnect", () => { console.log(`Client disconnected: ${socket.id}`); }); // Example custom event socket.on("send-message", (data) => { console.log("Message received:", data); io.emit("receive-message", data); }); }); return io; }; export const getIO = () => { if (!io) { throw new Error( "Socket.io not initialized. Call initSocketIO(server) first." ); } return io; };