Bird
Raised Fist0
Node.jsframework~10 mins

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

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
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

Practice

(1/5)
1. What does it mean that Node.js uses a single-threaded non-blocking I/O model?
easy
A. Node.js blocks the main thread until each task completes.
B. Node.js runs one main thread but can handle many tasks without waiting for each to finish.
C. Node.js uses multiple threads to run tasks in parallel.
D. Node.js cannot handle multiple tasks at the same time.

Solution

  1. Step 1: Understand single-threaded meaning

    Node.js runs on one main thread, unlike some systems that use many threads.
  2. Step 2: Understand non-blocking I/O meaning

    It does not wait for tasks like file reads to finish before moving on; it uses callbacks or events.
  3. Final Answer:

    Node.js runs one main thread but can handle many tasks without waiting for each to finish. -> Option B
  4. Quick Check:

    Single-threaded + non-blocking = handle many tasks without waiting [OK]
Hint: Single thread means one main path; non-blocking means no waiting [OK]
Common Mistakes:
  • Thinking Node.js uses multiple threads for tasks
  • Assuming Node.js waits for each task to finish before continuing
  • Confusing blocking with non-blocking I/O
2. Which of the following is the correct way to write a non-blocking file read in Node.js?
easy
A. fs.readFile('file.txt', (err, data) => { if (err) throw err; console.log(data); });
B. const data = fs.readFileSync('file.txt'); console.log(data);
C. const data = fs.readFile('file.txt'); console.log(data);
D. fs.readFile('file.txt'); console.log('done');

Solution

  1. Step 1: Identify non-blocking syntax

    Non-blocking file read uses fs.readFile with a callback to handle data after reading.
  2. Step 2: Check options for callback usage

    fs.readFile('file.txt', (err, data) => { if (err) throw err; console.log(data); }); uses fs.readFile with a callback function correctly handling error and data.
  3. Final Answer:

    fs.readFile('file.txt', (err, data) => { if (err) throw err; console.log(data); }); -> Option A
  4. Quick Check:

    Non-blocking file read uses callback = fs.readFile('file.txt', (err, data) => { if (err) throw err; console.log(data); }); [OK]
Hint: Non-blocking uses callbacks, blocking uses sync functions [OK]
Common Mistakes:
  • Using synchronous readFileSync for non-blocking tasks
  • Calling readFile without a callback
  • Expecting immediate data return from async calls
3. What will the following Node.js code output?
console.log('Start');
setTimeout(() => { console.log('Timeout done'); }, 0);
console.log('End');
medium
A. Start\nEnd\nTimeout done
B. End\nStart\nTimeout done
C. Timeout done\nStart\nEnd
D. Start\nTimeout done\nEnd

Solution

  1. Step 1: Understand synchronous logs

    console.log('Start') runs immediately and prints 'Start'.
  2. Step 2: Understand setTimeout with 0 delay

    setTimeout callback runs after current code finishes, so 'Timeout done' prints last.
  3. Step 3: Understand console.log('End')

    This runs immediately after 'Start', printing 'End' before the timeout callback.
  4. Final Answer:

    Start End Timeout done -> Option A
  5. Quick Check:

    Sync logs first, then async callback = Start\nEnd\nTimeout done [OK]
Hint: setTimeout with 0ms runs after current code finishes [OK]
Common Mistakes:
  • Assuming setTimeout runs immediately
  • Mixing order of synchronous and asynchronous logs
  • Thinking 0ms delay means instant execution
4. Identify the error in this Node.js code snippet using non-blocking I/O:
const fs = require('fs');
let content;
fs.readFile('data.txt', (err, data) => {
  if (err) throw err;
  content = data.toString();
});
console.log(content);
medium
A. The callback function is missing the error parameter.
B. The readFile method should be readFileSync for async code.
C. The variable content is logged before the file read completes.
D. The data.toString() call is invalid.

Solution

  1. Step 1: Understand async callback timing

    readFile runs asynchronously, so the callback runs after console.log(content).
  2. Step 2: Check when content is logged

    console.log(content) runs immediately, before content is assigned inside the callback.
  3. Final Answer:

    The variable content is logged before the file read completes. -> Option C
  4. Quick Check:

    Async callback runs later, so content is undefined at log [OK]
Hint: Async callbacks run later; log inside callback to see data [OK]
Common Mistakes:
  • Logging async data before callback runs
  • Confusing sync and async readFile methods
  • Ignoring error parameter in callback
5. You want to read two files in Node.js and then combine their contents. Which approach correctly uses non-blocking I/O to do this?
hard
A. Use fs.readFile once and then read the second file inside the first callback synchronously.
B. Use fs.readFileSync twice and then combine results synchronously.
C. Call fs.readFile twice with callbacks, combine results immediately after calling both without waiting.
D. Call fs.readFile twice with callbacks, combine results inside the second callback only after both finish.

Solution

  1. Step 1: Understand non-blocking file reads

    Each fs.readFile runs asynchronously and needs a callback to get data.
  2. Step 2: Combine results after both reads finish

    To combine contents, wait for both callbacks to complete, then combine inside the second callback or use coordination logic.
  3. Final Answer:

    Call fs.readFile twice with callbacks, combine results inside the second callback only after both finish. -> Option D
  4. Quick Check:

    Combine after both async reads finish = Call fs.readFile twice with callbacks, combine results inside the second callback only after both finish. [OK]
Hint: Combine data only after both async callbacks complete [OK]
Common Mistakes:
  • Combining data before async reads finish
  • Using synchronous reads in async code
  • Nesting sync reads inside async callbacks incorrectly