Synchronous File Operations

Understand when synchronous file APIs block the event loop and when they are acceptable.

Lesson content

🎯 Goal By the end of this lesson, you'll understand: What are Synchronous File Operations? Why do we use them? Common synchronous methods Advantages and disadvantages Real-world examples Interview questions What are Synchronous File Operations? Synchronous File Operations execute one operation at a time . Node.js waits until the current file operation is completed before executing the next line of code. Simple Definition: Synchronous operations block the execution until the task is finished. Why Do We Need Synchronous Operations? Sometimes we need to ensure that a file operation completes before the next step starts. Examples: Reading configuration files during application startup Running setup scripts Writing logs in small utility scripts Real-Life Example πŸ“š Imagine borrowing a book from a library. Request Book β”‚ β–Ό Wait Until Book Arrives β”‚ β–Ό Read Book β”‚ β–Ό Request Another Book You cannot move to the next step until the current one finishes. Import FS Module const fs = require ( "fs" ); 1. Read File Synchronously const fs = require ( "fs" ); const data = fs . readFileSync( "test.txt" , "utf8" ); console . log( data ); Output Hello Node.js 2. Write File Synchronously const fs = require ( "fs" ); fs . writeFileSync( "test.txt" , "Hello World" ); console . log( "File Created" ); Output File Created 3. Append File Synchronously const fs = require ( "fs" ); fs . appendFileSync( "test.txt" , " \n Welcome" ); console . log( "Data Added" ); Output Data Added 4. Rename File Synchronously const fs = require ( "fs" ); fs . renameSync( "test.txt" , "new.txt" ); console . log( "Renamed" ); 5. Delete File Synchronously const fs = require ( "fs" ); fs . unlinkSync( "new.txt" ); console . log( "Deleted" ); 6. Create Folder Synchronously const fs = require ( "fs" ); fs . mkdirSync( "Demo" ); console . log( "Folder Created" ); 7. Delete Folder Synchronously const fs = require ( "fs" ); fs . rmSync( "Demo" , { recursive: true , force: true }); console . log( "Folder Deleted" ); 8. Read Directory const fs = require ( "fs" ); const files = fs . readdirSync( "./" ); console . log( files ); Output [ "app.js", "package.json", "test.txt" ] 9. Get File Information const fs = require ( "fs" ); const stats = fs . statSync( "test.txt" ); console . log( stats . size); console . log( stats . isFile()); Output 1024 true How Synchronous Operations Work Application β”‚ β–Ό readFileSync() β”‚ β–Ό Wait... β”‚ β–Ό Read Complete β”‚ β–Ό Next Line Executes Synchronous vs Asynchronous Synchronous Asynchronous Blocks execution Doesn't block execution One task at a time Multiple tasks can continue readFileSync() readFile() Simpler for scripts Better for servers Example const fs = require ( "fs" ); console . log( "Start" ); const data = fs . readFileSync( "test.txt" , "utf8" ); console . log( data ); console . log( "End" ); Output Start Hello Node.js End The program waits until the file is fully read before printing "End" . Where Are Synchronous Operations Used? βœ… Configuration file loading βœ… Startup scripts βœ… Build tools βœ… CLI applications βœ… Small utility scripts βœ… Testing Advantages βœ… Easy to understand βœ… Sequential execution βœ… Good for small scripts βœ… No callbacks or Promises required Disadvantages ❌ Blocks the Event Loop ❌ Slower for web servers ❌ Poor scalability ❌ Not suitable for handling many concurrent users Interview Question What is the output? const fs = require ( "fs" ); console . log( "Start" ); fs . writeFileSync( "test.txt" , "Hello" ); console . log( "End" ); Output Start End Reason: writeFileSync() completes first, then the next line executes. Best Practices βœ… Use synchronous methods during application startup or in CLI tools. βœ… Use asynchronous methods in production web servers. βœ… Always use try...catch to handle errors. try { const data = fs . readFileSync( "test.txt" , "utf8" ); console . log( data ); } catch ( err ) { console . error( err . message); } ❌ Avoid synchronous file operations inside API request handlers because they block the Event Loop. Key Points βœ… Synchronous file operations block execution until completion. βœ… They are simple and execute code sequentially. βœ… Common methods include readFileSync() , writeFileSync() , appendFileSync() , renameSync() , unlinkSync() , mkdirSync() , rmSync() , readdirSync() , and statSync() . βœ… Best suited for startup tasks, scripts, and CLI applications. βœ… Avoid them in high-performance Node.js servers. 🧠 Easy Formula Need File Operation β”‚ β–Ό Sync Method β”‚ β–Ό Wait Until Complete β”‚ β–Ό Execute Next Line readFileSync() β†’ Read writeFileSync() β†’ Create/Overwrite appendFileSync() β†’ Add Data renameSync() β†’ Rename unlinkSync() β†’ Delete File mkdirSync() β†’ Create Folder rmSync() β†’ Delete Folder readdirSync() β†’ Read Directory statSync() β†’ File Information Remember: ⏳ Synchronous = Wait until the operation finishes. πŸ“‚ Simple but blocks the Event Loop. πŸš€ Best for startup scripts, CLI tools, and configuration loadingβ€”not for production request handling.