Performance: Reading files with promises (fs.promises)
This affects how quickly file data is read and made available without blocking the main event loop, improving server responsiveness.
Jump into concepts and practice - no test required
import { promises as fs } from 'fs'; async function readFile() { const data = await fs.readFile('file.txt', 'utf8'); console.log(data); } readFile();
const fs = require('fs'); const data = fs.readFileSync('file.txt', 'utf8'); console.log(data);
| Pattern | Event Loop Blocking | Throughput Impact | Responsiveness | Verdict |
|---|---|---|---|---|
| Synchronous fs.readFileSync | Blocks event loop | Reduces throughput | Poor (blocks input) | [X] Bad |
| Asynchronous fs.promises.readFile | Non-blocking | Improves throughput | Good (responsive) | [OK] Good |
fs.promises.readFile return when reading a file in Node.js?await or .then() to get the file content asynchronously.fs.promises.readFile with async/await?fs.promises.readFile.await with fs.promises.readFile. const data = fs.promises.readFile('file.txt'); misses await, C uses callback style which is incorrect here, and D uses wrong module method.import { promises as fs } from 'fs';
async function read() {
const content = await fs.readFile('example.txt', 'utf8');
console.log(typeof content);
}
read();typeof operator on a string returns 'string', so the console logs 'string'.import { promises as fs } from 'fs';
async function readFile() {
const data = fs.readFile('data.txt', 'utf8');
console.log(data);
}
readFile();fs.readFile returns a promise, so to get the file content, you must await it.await, data is a promise object, so logging it shows a promise, not file content.['a.txt', 'b.txt', 'c.txt'] concurrently using fs.promises.readFile and get their contents as strings. Which code snippet correctly does this?Promise.all to await all results.