0
0
Node.jsframework~10 mins

Single-threaded non-blocking I/O concept in Node.js - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to read a file asynchronously using Node.js.

Node.js
const fs = require('fs');
fs.readFile('example.txt', 'utf8', (err, data) => {
  if (err) throw err;
  console.log(data);
});
console.log('Reading file...');
// This is non-blocking because [1]
Drag options to blanks, or click blank then click option'
AreadFile blocks the thread
Bconsole.log waits for readFile
CreadFile is synchronous
DreadFile runs asynchronously
Attempts:
3 left
💡 Hint
Common Mistakes
Thinking readFile is synchronous and blocks execution
Assuming console.log waits for readFile to finish
2fill in blank
medium

Complete the code to create a simple HTTP server that handles requests without blocking.

Node.js
const http = require('http');
const server = http.createServer((req, res) => {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World');
});
server.listen(3000);
console.log('Server running at http://localhost:3000/');
// This server is non-blocking because it uses [1]
Drag options to blanks, or click blank then click option'
Awhile(true) loops
Bsynchronous file reads
Casynchronous callbacks
Dblocking loops
Attempts:
3 left
💡 Hint
Common Mistakes
Thinking the server blocks while waiting for requests
Confusing synchronous and asynchronous code
3fill in blank
hard

Fix the error in the code to correctly use non-blocking I/O for reading a file.

Node.js
const fs = require('fs');
const data = fs.readFileSync('data.txt', 'utf8');
console.log(data);
console.log('File read complete');
// To make this non-blocking, replace readFileSync with [1]
Drag options to blanks, or click blank then click option'
AreadFile
BreadFileSync
CwriteFileSync
DwriteFile
Attempts:
3 left
💡 Hint
Common Mistakes
Using readFileSync which blocks execution
Confusing readFile and writeFile functions
4fill in blank
hard

Fill both blanks to create a non-blocking timer that logs a message after 2 seconds.

Node.js
console.log('Start');
setTimeout(() => {
  console.log([1]);
}, [2]);
console.log('End');
Drag options to blanks, or click blank then click option'
A'Timer done'
B2000
C1000
D'Done'
Attempts:
3 left
💡 Hint
Common Mistakes
Using synchronous delay instead of setTimeout
Setting the wrong delay time
5fill in blank
hard

Fill all three blanks to create a Promise that resolves after 1 second and logs the result.

Node.js
const wait = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve([1]);
  }, [2]);
});
wait.then((message) => {
  console.log([3]);
});
Drag options to blanks, or click blank then click option'
A'Success'
B1000
Cmessage
D'Done'
Attempts:
3 left
💡 Hint
Common Mistakes
Not resolving the Promise with a value
Logging a string instead of the resolved message variable