Node.js uses the system kernel to perform I/O operations asynchronously. It registers callbacks that run when the operation finishes, allowing the single JavaScript thread to continue running other code.
console.log('Start'); setTimeout(() => console.log('Timeout'), 0); console.log('End');
The synchronous console.log('Start') runs first, then console.log('End'). The setTimeout callback runs last, even with 0 delay, because it is queued in the event loop.
const fs = require('fs'); const data = fs.readFileSync('file.txt'); console.log('File read');
readFileSync is a synchronous function that blocks the event loop until the file is fully read. This stops other JavaScript code from running during that time.
fs/promises module provides Promise-based versions of fs functions. Using fs.readFile from fs/promises returns a Promise that can be handled with .then().
console.log('1'); setTimeout(() => console.log('2'), 0); Promise.resolve().then(() => console.log('3')); console.log('4');
First, synchronous logs '1' and '4' run. Then Promise callbacks (microtasks) run, logging '3'. Finally, setTimeout callbacks (macrotasks) run, logging '2'.