🌍 NodeJS · subject

NodeJS Networking Syllabus

The Networking syllabus for NodeJS in full: 2 chapters and 6 topics, every one listed below, plus 50 Networking flashcards with answers.

2Chapters
6Topics
50Flashcards

Networking syllabus: all 2 chapters

Expand any chapter to see its topics and sub-topics.

  1. HTTP Module

    3 topics
    • Creating a Server
    • Handling Requests and Responses
    • Routing
  2. WebSockets

    3 topics
    • Introduction to WebSockets
    • Implementing WebSocket Server
    • Real-time Communication

NodeJS Networking flashcards — 50 questions with answers

  1. Which core Node.js module is used to create an HTTP server, and how is it imported?

    The built-in `http` module. It is imported with `const http = require('http');` (CommonJS) or `import http from 'node:http';` (ESM). No installation is needed since it ships with Node.js.

  2. Write the minimal Node.js code to create an HTTP server that listens on port 3000.

    const http = require('http'); const server = http.createServer((req, res) => { res.end('Hello'); }); server.listen(3000);

  3. What two objects does the request-listener callback passed to http.createServer() receive, and what do they represent?

    It receives `(req, res)`: `req` is an http.IncomingMessage (the incoming request — a readable stream) and `res` is an http.ServerResponse (the outgoing response — a writable stream).

  4. What is the difference between res.write() and res.end() on an http.ServerResponse?

    res.write() sends a chunk of the response body and can be called multiple times to stream data. res.end() signals the response is complete; it optionally sends a final chunk and must be called to finish every response, or the client will hang.

  5. How do you set the HTTP status code and response headers before sending a body in Node's http module?

    Use `res.writeHead(statusCode, headersObject)`, e.g. `res.writeHead(200, { 'Content-Type': 'text/html' });`. Alternatively set `res.statusCode = 200;` and `res.setHeader('Content-Type', 'text/html');` individually before the first write.

  6. Why must Node.js request bodies be read from the stream in chunks rather than accessed directly?

    Because `req` is a readable stream — the body arrives asynchronously as data chunks. You collect it via the 'data' event (accumulating a Buffer) and process it on the 'end' event, since the full body is not available synchronously on the request object.

  7. Write the event-based pattern to collect a full request body in Node.js.

    let body = []; req.on('data', chunk => { body.push(chunk); }); req.on('end', () => { body = Buffer.concat(body).toString(); // parse/use body });

  8. Which two properties of the req (IncomingMessage) object identify what the client is asking for, and are the basis of routing?

    `req.url` (the request path, e.g. '/users') and `req.method` (the HTTP verb, e.g. 'GET' or 'POST'). Routing logic branches on these two values.

  9. What does server.listen(port, host, callback) do, and is it synchronous?

    It binds the server to the given port/host and starts accepting connections. It is asynchronous — the server does not begin listening immediately; the optional callback fires once the 'listening' event occurs and the server is ready.

  10. By default, is the Content-Type header set for a Node.js http response, and why does it matter?

    No default meaningful type is guaranteed for your content; you should explicitly set it. It matters because the client (browser) uses Content-Type to decide how to interpret the body — e.g. 'text/html' renders as a page, 'application/json' is parsed as JSON, 'text/plain' shows raw text.

  11. What is 'routing' in the context of a web server?

    Routing is the process of mapping an incoming request's URL path and HTTP method to the specific handler code that should produce the response. It directs different requests to different logic.

  12. Show a basic manual routing structure in vanilla Node.js using req.url and req.method.

    if (req.url === '/' && req.method === 'GET') { // home handler } else if (req.url === '/users' && req.method === 'POST') { // create user } else { res.writeHead(404); res.end('Not Found'); }

  13. What HTTP status code should a route handler return when no matching route is found?

    404 (Not Found). It signals to the client that the requested resource/path does not exist on the server.

  14. In Express.js, what is the general signature of a route definition?

    `app.METHOD(path, handler)`, e.g. `app.get('/users', (req, res) => { ... })`. METHOD is the lowercased HTTP verb (get, post, put, delete), path is the URL pattern, and handler is `(req, res, next) => {...}`.

  15. How do you define and read a route (path) parameter in Express?

    Declare it with a colon in the path, e.g. `app.get('/users/:id', ...)`, and read it from `req.params.id`. Route params capture dynamic segments of the URL.

  16. What is the difference between a route (path) parameter and a query string parameter?

    A route parameter is part of the URL path (e.g. /users/42 → req.params.id) and typically identifies a resource. A query parameter follows a '?' (e.g. /search?q=node → req.query.q) and typically carries optional filters/options.

  17. What is middleware in Express, and what three arguments does a middleware function receive?

    Middleware is a function that runs during the request-response cycle, able to inspect/modify req and res or end the response. It receives `(req, res, next)`; calling `next()` passes control to the next middleware/handler in the stack.

  18. What happens if an Express middleware neither sends a response nor calls next()?

    The request hangs — control is never passed on and no response is sent, so the client eventually times out. Every middleware must either end the response or call next().

  19. Compare the standard HTTP request-response model with WebSockets in terms of communication direction.

    HTTP is half-duplex/unidirectional per exchange and client-initiated: the client requests, the server responds, then the connection work ends. WebSockets are full-duplex and persistent: after the handshake, either side can send messages at any time over one open connection.

  20. What protocol identifiers (URI schemes) are used for WebSocket connections?

    `ws://` for an unencrypted WebSocket connection and `wss://` for an encrypted (TLS/SSL) WebSocket connection, analogous to http:// and https://.

Show the other 30 Networking flashcards
  1. How is a WebSocket connection established? Describe the handshake.

    It begins as an HTTP request with an `Upgrade: websocket` and `Connection: Upgrade` header. If the server agrees, it responds with status 101 (Switching Protocols), and the underlying TCP connection is then upgraded from HTTP to the WebSocket protocol for full-duplex messaging.

  2. What HTTP status code indicates a successful WebSocket protocol upgrade?

    101 Switching Protocols. It tells the client the server has agreed to switch from HTTP to the WebSocket protocol on the same connection.

  3. Why are WebSockets preferred over HTTP polling for real-time applications?

    Polling repeatedly opens HTTP requests to check for updates, wasting bandwidth and adding latency and overhead. WebSockets keep one persistent connection where the server can push data instantly, giving lower latency and far less overhead for frequent bidirectional updates.

  4. What is the difference between HTTP polling, long polling, and WebSockets?

    Polling: client requests updates at fixed intervals regardless of new data. Long polling: server holds the request open until data is available, then client re-requests. WebSockets: a single persistent full-duplex connection where the server pushes data immediately with no repeated requests.

  5. Which popular npm library provides a WebSocket implementation for Node.js, and how is a server created with it?

    The `ws` library. A server is created with `const { WebSocketServer } = require('ws'); const wss = new WebSocketServer({ port: 8080 });` (or by attaching to an existing HTTP server via the `server` option).

  6. Using the `ws` library, how do you handle a new client connecting to the WebSocket server?

    Listen for the 'connection' event: wss.on('connection', (ws) => { // ws is the individual client socket ws.on('message', (data) => { /* handle */ }); });

  7. With the `ws` library, how does a server send a message to a single connected client?

    Call `ws.send(data)` on that client's socket object, e.g. `ws.send('hello');`. The data can be a string or binary (Buffer/ArrayBuffer).

  8. What key WebSocket events should a server typically handle for each connection?

    'message' (data received from the client), 'close' (client disconnected), and 'error' (connection error). The server-level 'connection' event fires for each new client.

  9. How do you attach a `ws` WebSocket server to an existing Node.js HTTP server so both share a port?

    Pass the HTTP server to the WebSocketServer: `const wss = new WebSocketServer({ server: httpServer });`. This lets HTTP requests and WebSocket upgrade requests be served on the same port.

  10. What does 'broadcasting' mean in a WebSocket server, and how is it implemented with `ws`?

    Broadcasting means sending a message to all connected clients. With `ws` you iterate the server's client set: wss.clients.forEach(client => { if (client.readyState === WebSocket.OPEN) client.send(msg); });

  11. What are the four WebSocket readyState values and their meanings?

    CONNECTING (0) — handshake in progress; OPEN (1) — connection established, ready to communicate; CLOSING (2) — close handshake started; CLOSED (3) — connection closed or could not open.

  12. Before calling client.send() during a broadcast, why check client.readyState === WebSocket.OPEN?

    Because sending to a socket that is CONNECTING, CLOSING, or CLOSED throws an error or fails silently. Checking readyState === OPEN (1) ensures the client is ready to receive, preventing errors on stale/closing connections.

  13. On the browser (client) side, how do you open a WebSocket connection and listen for messages?

    const socket = new WebSocket('ws://localhost:8080'); socket.onopen = () => socket.send('hi'); socket.onmessage = (event) => console.log(event.data); The browser's built-in WebSocket API also supports onclose and onerror handlers.

  14. What is Socket.IO, and how does it differ from the raw WebSocket/`ws` protocol?

    Socket.IO is a higher-level real-time library built on top of WebSockets (with fallbacks like HTTP long polling). It adds features like automatic reconnection, rooms/namespaces, event-based named messages, and broadcasting. Raw WebSockets provide only the basic bidirectional message channel.

  15. In Socket.IO, what are 'rooms' and what are they used for?

    Rooms are arbitrary named channels a socket can join or leave (e.g. `socket.join('room1')`). They let the server target messages to a subset of clients, e.g. `io.to('room1').emit(...)`, which is useful for chat rooms, game lobbies, or per-user channels.

  16. In Socket.IO, what is the difference between socket.emit(), io.emit(), and socket.broadcast.emit()?

    socket.emit() sends only to that one client. io.emit() sends to every connected client including the sender. socket.broadcast.emit() sends to all connected clients except the sender.

  17. What is a 'namespace' in Socket.IO?

    A namespace is a communication channel that lets you split the connection logic over a single shared connection, e.g. `io.of('/admin')`. It allows separating concerns (different endpoints/features) while reusing the same underlying WebSocket.

  18. What is a heartbeat / ping-pong mechanism in WebSockets and why is it needed?

    It is periodic control frames (ping from one side, pong in reply) used to verify the connection is still alive and to keep it open through proxies/firewalls. It detects dead/half-open connections so the server can terminate stale clients.

  19. What CORS-related consideration differs between HTTP requests and WebSocket connections?

    WebSockets are not restricted by the browser's same-origin CORS policy in the same way as HTTP (no preflight); the browser sends an `Origin` header but does not block the connection. Therefore the server must validate the Origin header itself to prevent cross-site WebSocket hijacking.

  20. Give three canonical use cases where WebSockets/real-time communication are the right choice.

    Chat/messaging apps, live notifications and feeds (sports scores, stock tickers), and collaborative or multiplayer applications (shared documents, online games) — anywhere the server must push frequent low-latency updates to clients.

  21. What does the 'upgrade' event on a Node.js http.Server allow you to do?

    It fires when a client requests a protocol upgrade (e.g. to WebSocket) via the Upgrade header. Handling `server.on('upgrade', (req, socket, head) => {...})` lets you take over the raw TCP socket to complete the WebSocket handshake, which is how libraries integrate WS with an HTTP server.

  22. What is the purpose of the Sec-WebSocket-Key and Sec-WebSocket-Accept headers in the handshake?

    The client sends a random base64 `Sec-WebSocket-Key`. The server hashes it with a fixed GUID using SHA-1, base64-encodes the result, and returns it as `Sec-WebSocket-Accept`. This confirms the server understood the upgrade request and completes the handshake.

  23. How does a WebSocket close handshake work, and what is a close code?

    Either side sends a close control frame, optionally with a numeric status code and reason; the peer replies with its own close frame, then the TCP connection is torn down. Close codes (e.g. 1000 = normal closure, 1001 = going away, 1006 = abnormal) indicate why the connection ended.

  24. Can WebSocket messages carry binary data, and how does that compare to HTTP?

    Yes — WebSocket frames support both text (UTF-8) and binary payloads (Blob/ArrayBuffer/Buffer) natively with low framing overhead. HTTP can also carry binary but each transfer needs a full request/response cycle, whereas WebSocket streams frames over the persistent connection.

  25. When building a JSON API route in Node.js, how do you send a JSON response correctly?

    Set the header and stringify the object: res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify(data)); In Express simply use `res.json(data)`, which sets the header and serializes automatically.

  26. What is the difference between res.send() and res.json() in Express?

    res.send() infers the Content-Type from the argument (string → text/html, object → JSON, Buffer → octet-stream). res.json() always serializes the argument as JSON and sets Content-Type to application/json, even for null/undefined/primitives.

  27. Why should scaling a WebSocket application across multiple server instances use a message broker/adapter (e.g. Redis)?

    Because each server instance only holds its own set of connected clients in memory. To broadcast across all instances, a shared pub/sub backplane (like the Socket.IO Redis adapter) relays messages between servers so a client on one instance receives events emitted from another.

  28. What is backpressure in the context of a WebSocket (or any writable stream) server?

    Backpressure occurs when data is produced faster than the socket can send it, causing the send buffer to grow. In `ws` you can inspect `ws.bufferedAmount`; if it grows unbounded you should pause/throttle sending to avoid memory exhaustion.

  29. How does an HTTP keep-alive connection differ from a WebSocket connection?

    HTTP keep-alive reuses one TCP connection for multiple sequential request-response pairs, but communication is still client-initiated and half-duplex per exchange. A WebSocket permanently upgrades the connection to full-duplex, allowing unsolicited server-to-client messages at any time.

  30. What is the typical event flow for a real-time chat message using a WebSocket server?

    1) A client sends a message over its socket ('message' event on the server). 2) The server optionally validates/persists it. 3) The server broadcasts it to the relevant clients (all, a room, or others) via send/emit. 4) Each recipient's client receives it on its 'message'/onmessage handler and updates the UI — all without any new HTTP request.

NodeJS Networking FAQ

What is in the NodeJS Networking syllabus?

NodeJS Networking is split into 2 chapters: HTTP Module and WebSockets. Together they contain 6 topics.

How many chapters are in NodeJS Networking?

2 chapters, containing 6 topics. The largest chapter is HTTP Module, with 3 topics.

Are there flashcards for NodeJS Networking?

Yes — a 50-card Networking deck, printed in full in the flashcards section of this page and available in the Examius app with spaced repetition. The free plan covers one exam of your choice, including its flashcards; Examius Pro, a one-time purchase, unlocks every other exam and deck.