Performance: Reading files asynchronously with callbacks
This affects how fast the page or server can respond while waiting for file data, impacting input responsiveness and overall user experience.
Jump into concepts and practice - no test required
const fs = require('fs'); fs.readFile('file.txt', 'utf8', (err, data) => { if (err) throw err; console.log(data); });
const fs = require('fs'); const data = fs.readFileSync('file.txt', 'utf8'); console.log(data);
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Synchronous file read | N/A | Blocks event loop | N/A | [X] Bad |
| Asynchronous file read with callback | N/A | Non-blocking | N/A | [OK] Good |
fs.readFile with a callback in Node.js?fs.readFile rolefs.readFile reads files without stopping other code from running.fs.readFile is synchronousdata.txt asynchronously using fs.readFile with a callback?err first, then data.example.txt contains the text "Hello World"?const fs = require('fs');
fs.readFile('example.txt', (err, data) => {
if (err) {
console.log('Error reading file');
} else {
console.log(data.toString());
}
});data contains file content as a Buffer.data.toString() converts Buffer to readable text, so it prints "Hello World".toString() to read file content as text [OK]const fs = require('fs');
fs.readFile('notes.txt', (data, err) => {
if (err) {
console.error('Failed to read file');
} else {
console.log(data.toString());
}
});err as first parameter, then data.data to receive error and err to receive data, breaking error check.file1.txt, file2.txt, and file3.txt. Which approach correctly ensures the files are read and logged in sequence using callbacks?fs.readFile without nesting may log files out of order.fs.readFile for each file inside the previous file's callback -> Option A