Performance: Single-threaded non-blocking I/O concept
This concept affects how fast Node.js can handle multiple I/O tasks without blocking the main thread, improving responsiveness and throughput.
Jump into concepts and practice - no test required
const fs = require('fs'); fs.readFile('file1.txt', (err, data1) => { if (err) throw err; fs.readFile('file2.txt', (err, data2) => { if (err) throw err; console.log(data1.toString(), data2.toString()); }); });
const fs = require('fs'); const data1 = fs.readFileSync('file1.txt'); const data2 = fs.readFileSync('file2.txt'); console.log(data1.toString(), data2.toString());
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Synchronous I/O | N/A | Blocks event loop | N/A | [X] Bad |
| Asynchronous non-blocking I/O | N/A | Event loop free | N/A | [OK] Good |
single-threaded non-blocking I/O model?fs.readFile with a callback to handle data after reading.fs.readFile with a callback function correctly handling error and data.console.log('Start');
setTimeout(() => { console.log('Timeout done'); }, 0);
console.log('End');const fs = require('fs');
let content;
fs.readFile('data.txt', (err, data) => {
if (err) throw err;
content = data.toString();
});
console.log(content);fs.readFile runs asynchronously and needs a callback to get data.fs.readFile twice with callbacks, combine results inside the second callback only after both finish. [OK]