How do you implement a WebSocket server in Node.js using the `ws` library?

Answer

The ws library is the most popular bare-bones WebSocket server for Node.js. Install with npm install ws. Basic server setup: const WebSocket = require('ws'); const wss = new WebSocket.Server({ port: 8080 }); wss.on('connection', (ws, req) => { ws.on('message', (data) => { console.log('Received:', data.toString()); ws.send('Echo: ' + data); }); ws.on('close', () => console.log('Client disconnected')); ws.send('Welcome!'); }). To broadcast to all clients: wss.clients.forEach(client => { if (client.readyState === WebSocket.OPEN) client.send(message); }). The ws library integrates with existing HTTP servers (Express, Fastify) by attaching to the server instance rather than creating its own port, enabling WebSocket and HTTP on the same port.