Consider a Node.js server that uses long polling as a fallback when WebSocket is unavailable. What will the client receive if the server holds the request open until new data arrives?
const http = require('http'); let dataAvailable = false; http.createServer((req, res) => { if (req.url === '/poll') { if (dataAvailable) { res.end('New data'); dataAvailable = false; } else { // Hold request open setTimeout(() => { res.end('No new data'); }, 5000); } } else { res.end('Hello'); } }).listen(3000);
Think about how the server responds based on the dataAvailable flag and the timeout.
The server checks if dataAvailable is true. If yes, it responds immediately with 'New data'. If not, it holds the request open for 5 seconds before responding with 'No new data'. This simulates long polling fallback behavior.
Which option contains a syntax error that would prevent a Node.js long polling server from running?
const http = require('http'); http.createServer((req, res) => { if (req.url === '/poll') { setTimeout(() => { res.end('Data'); }, 3000); } else { res.end('OK'); } }).listen(3000);
Check the parentheses matching in the setTimeout call.
Option C is correct because the setTimeout call is missing a closing parenthesis, causing a syntax error. Other options are either stylistic or incorrect.
Given this server code, what will the client receive on the second poll request?
const http = require('http'); let dataQueue = ['first', 'second']; http.createServer((req, res) => { if (req.url === '/poll') { if (dataQueue.length > 0) { res.end(dataQueue.shift()); } else { setTimeout(() => { res.end('no data'); }, 2000); } } else { res.end('welcome'); } }).listen(3000);
Think about how dataQueue.shift() changes the queue after each request.
On the first poll, 'first' is removed and sent. On the second poll, 'second' is removed and sent immediately. Only after the queue is empty does the server wait 2 seconds and send 'no data'.
Examine the code below. Why does the client never get a response?
const http = require('http'); let hasData = false; http.createServer((req, res) => { if (req.url === '/poll') { if (hasData) { res.end('Data ready'); hasData = false; } else { // Missing response or timeout here } } else { res.end('Hello'); } }).listen(3000);
Check what happens when hasData is false.
The else block for when hasData is false does not send any response or close the connection. This causes the client to wait indefinitely, so no response is received.
Which reason best explains why long polling is used as a fallback method for real-time communication when WebSocket is unavailable?
Think about how long polling mimics real-time updates over traditional HTTP.
Long polling keeps the client request open until the server has new data, allowing near real-time updates without WebSocket. It does not use WebSocket internally and does not close connections immediately.