0
0
Node.jsframework~8 mins

Writing files in Node.js - Performance & Optimization

Choose your learning style9 modes available
Performance: Writing files
MEDIUM IMPACT
This affects page load speed indirectly by blocking the event loop during file write operations, impacting responsiveness and user experience.
Writing data to a file in a Node.js server
Node.js
import { writeFile } from 'node:fs/promises';
await writeFile('output.txt', 'Hello World');
Uses asynchronous non-blocking API, allowing other operations to run while writing the file.
📈 Performance GainNon-blocking write, keeps event loop free, improves INP
Writing data to a file in a Node.js server
Node.js
const fs = require('fs');
fs.writeFileSync('output.txt', 'Hello World');
Blocks the Node.js event loop until the file write completes, causing delays in handling other requests.
📉 Performance CostBlocks event loop for duration of write, increasing INP and slowing response
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Synchronous writeFileSync000[X] Bad
Asynchronous writeFile (promises)000[OK] Good
Rendering Pipeline
File writing in Node.js does not directly affect browser rendering but impacts server responsiveness, which affects how fast the client receives data.
Event Loop
I/O Operations
⚠️ BottleneckBlocking synchronous file writes block the event loop, delaying all other tasks.
Core Web Vital Affected
INP
This affects page load speed indirectly by blocking the event loop during file write operations, impacting responsiveness and user experience.
Optimization Tips
1Never use synchronous file writes in production server code.
2Prefer asynchronous file system APIs to keep the event loop free.
3Monitor event loop blocking to maintain good interaction responsiveness.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance problem with using fs.writeFileSync in Node.js?
AIt blocks the event loop, delaying other operations.
BIt increases the file size unnecessarily.
CIt causes memory leaks in the server.
DIt slows down the browser rendering directly.
DevTools: Performance
How to check: Record a performance profile while the server handles file writes; look for long tasks blocking the event loop.
What to look for: Long blocking tasks indicate synchronous file writes; shorter tasks with gaps indicate asynchronous writes.