CodeBlanks Logo Icon CodeBlanks

I/O callbacks

Learn I/O callbacks and the poll phase.

I/O callbacks

I/O callbacks run when file and network operations finish. In the poll phase the event loop collects completed I/O events and runs their callbacks. When fs.readFile finishes its callback runs here.

An ioCallbacks(events) function models this phase: the input [{name: 'read'}, {name: 'write'}] returns 'read,write'. events.map(e => e.name) takes each event's name, .join(',') combines them. This shows the poll phase processes I/O events in order. The output is read,write. In real Node.js these callbacks are queued by libuv; the event loop drains them all in the poll phase. The model is deterministic; no timing uncertainty.

Extracting event names

In this lesson we write the ioCallbacks function. The function takes an event array, extracts each event's name property, and joins them with a comma. This models the poll phase processing I/O events in order.

Example: events.map(e => e.name) gives ['read', 'write']. .join(',') yields 'read,write'. console.log(ioCallbacks([{name: 'read'}, {name: 'write'}])) prints read,write. map transforms each item; here from object to name string. join combines the array into a string. These two methods form a common pattern for summarizing the poll phase output. The output is deterministic.

Practice Write the I/O callback function

Write function ioCallbacks(events). Return events.map(e => e.name).join(','). Print console.log(ioCallbacks([{name: 'read'}, {name: 'write'}])).

Starter code

index.js
// Write an ioCallbacks function
// Take each event's name
// Join with a comma and print
// Call with [{name: 'read'}, {name: 'write'}]
// write here

Sample solution

index.js
function ioCallbacks(events) {
  return events.map(e => e.name).join(',');
}
console.log(ioCallbacks([{name: 'read'}, {name: 'write'}]));

Expected output

read,write

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 In which phase does the fs.readFile callback run?

  • poll Correct answer
  • timers
  • check
  • close

Explanation: I/O callbacks run in the poll phase.

2 Match each concept to its description

Term Meaning
poll phase Processes I/O events
map Transforms each item
join Combines array into string
fs.readFile File read I/O

3 Complete the map call

Question
return events.____(e => e.name).join(',');
Answer
return events.map(e => e.name).join(',');

Explanation: map turns each event into its name.

All lessons in Expert