Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to create a simple Node.js server that listens on port 3000.
Node.js
const http = require('http'); const server = http.createServer((req, res) => { res.end('Hello World'); }); server.listen([1]);
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using port 80 without proper permissions.
Choosing a port number that is already in use.
✗ Incorrect
The server listens on port 3000, which is a common port for development servers.
2fill in blank
mediumComplete the code to import the 'ws' library for WebSocket support.
Node.js
const WebSocket = [1]('ws');
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'import' without enabling ES modules.
Using 'fetch' which is for HTTP requests.
✗ Incorrect
In Node.js, 'require' is used to import modules like 'ws'.
3fill in blank
hardFix the error in the WebSocket server code by completing the missing method.
Node.js
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', function connection(ws) {
ws.[1]('Welcome to the server!');
}); Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'write' which is for streams.
Using 'emit' which triggers events.
✗ Incorrect
The 'send' method is used to send data to the connected WebSocket client.
4fill in blank
hardFill both blanks to broadcast a message to all connected clients.
Node.js
wss.clients.forEach(function each([1]) { if ([2].readyState === WebSocket.OPEN) { [2].send('Broadcast message'); } });
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names inconsistently.
Using undefined variable names.
✗ Incorrect
The variable 'ws' is commonly used to represent each WebSocket client in the loop.
5fill in blank
hardFill all three blanks to set up a real-time message event handler.
Node.js
wss.on('connection', function connection(ws) { ws.on('[1]', function incoming([2]) { console.log('Received: %s', [3]); }); });
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'connect' instead of 'message' event.
Using different names for the parameter and logged variable.
✗ Incorrect
The 'message' event listens for incoming messages, 'msg' is the parameter holding the message data.