Message
- Node.js course
- Advanced
- Lesson 40/83
- 5 min
Learn messaging with ws.send and ws.on('message').
The message event
When a message arrives from a client the "message" event fires. You catch it with ws.on("message", (data) => { ... }). data is a Buffer; to use it as a string you call data.toString().
Messages can be strings or binary. JSON messages are common: the client sends ws.send(JSON.stringify({ type: "chat", text: "hello" })), the server parses with JSON.parse(data.toString()). This gives structured communication. Catching errors in the message handler is a good habit; bad JSON should not crash the server.
Sending messages with ws.send
To send a message to a client: ws.send(data). data can be a string, Buffer, or object. For objects you use ws.send(JSON.stringify(obj)).
To send a message to all clients (broadcast) you iterate over wss.clients. wss.clients is a Set; each item is a ws connection. You send to everyone with clients.forEach((client) => client.send(msg)). This is the foundation of chat broadcast.
Practice Register a message handler
Create an EventEmitter. Listen for the "message" event with a handler. Then log "message ready".
Starter code
// import EventEmitter, create one
// listen for the message event
// log "message ready"Sample solution
const { EventEmitter } = require("events");
const ws = new EventEmitter();
ws.on("message", (data) => {});
console.log("message ready");Expected output
message ready
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What parameter does the message handler take?
- port
- css
- sql
- data (Buffer) Correct answer
Explanation: The handler takes data (a Buffer).
2 Match each piece to its role
| Term | Meaning |
|---|---|
ws.on("message") |
Listens for message |
ws.send |
Sends a message |
data.toString() |
Converts to string |
JSON.parse |
Parses |
3 Complete the event name
ws.on("____", (data) => { console.log(data.toString()); })
ws.on("message", (data) => { console.log(data.toString()); })
Explanation: The message event fires when a message arrives.