ws module
- Node.js course
- Advanced
- Lesson 37/83
- 5 min
Learn WebSocket servers with the ws module.
What is the ws module?
ws is the most popular lightweight WebSocket module for Node.js. WebSocket provides a bidirectional, persistent connection between server and client; unlike HTTP it does not reconnect per request.
Install: npm install ws. WebSocket is ideal for real-time apps: chat, live notifications, games. The ws module is low-level; for higher-level features use Socket.io. But ws is lighter and has less overhead. You import it with require("ws").
WebSocket vs HTTP
HTTP is request-response based: the client asks, the server answers, the connection closes. WebSocket keeps the connection open; either side can send a message at any time.
This is critical for real-time apps. In a chat app the server can push a new message instantly; it does not wait for the client to ask. WebSocket starts with an HTTP handshake, then upgrades to the WebSocket protocol. That is why it uses the same ports (80/443).
Practice Log the type of WebSocketServer
Import the WebSocketServer class from ws. Log typeof WebSocketServer.
Starter code
// import the module, get the server class
// log its typeSample solution
const { WebSocketServer } = require("ws");
console.log(typeof WebSocketServer);Expected output
function
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does the ws module provide?
- A persistent two-way connection Correct answer
- One-way HTTP
- File compression
- Network acceleration
Explanation: The ws module provides a bidirectional persistent connection.
2 Complete the module name
const { WebSocketServer } = require("____")
const { WebSocketServer } = require("ws")
Explanation: The ws module loads as 'ws'.
3 Match each piece to its role
| Term | Meaning |
|---|---|
ws |
WebSocket module |
WebSocketServer |
Server class |
npm install ws |
Installs the module |
require("ws") |
Imports the module |