MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
File System Operations: Sync, Async & Promises API (fs/promises)0%
Study Materials
Node.js & Express.jsProgress 0%
1.1Node.js Architecture, V8 Engine & Single-Threaded Event Loop1.2Call Stack, Callback Queue, Microtask Queue & Libuv Workers1.3Non-Blocking Asynchronous Code with Promises and Async/Await
2.1CommonJS vs ES Modules & Package.json Dependency Management2.2File System Operations: Sync, Async & Promises API (fs/promises)2.3EventEmitter Pattern & Custom Event Architecture2.4Buffers and Streams: Readable, Writable & Pipeline for Large Files
HomeTutorialsNode.js & Express.jsFile System Operations: Sync, Async & Promises API (fs/promises)
EventEmitter Pattern & Custom Event Architecture

File System Operations: Sync, Async & Promises API (fs/promises)

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

File system manipulation is a daily responsibility for backend engineers: reading configurations, saving user uploads, processing log files, and streaming large datasets. Node.js provides three distinct flavors of the fs (File System) module: Synchronous, Callback-based Asynchronous, and Promises-based Asynchronous (fs/promises).


1. The Three fs API Flavors

1. Synchronous (fs.readFileSync) - AVOID IN REQUEST HANDLERS

Blocks the entire Event Loop until the disk read finishes. Permissible ONLY during initial server boot to load config files.

1// DO NOT DO THIS inside an Express route handler!
2const data = fs.readFileSync('/var/log/system.log', 'utf8');

2. Callback-based (fs.readFile)

The historical Node.js pattern; executes asynchronously without blocking the main thread.

1fs.readFile('./config.json', 'utf8', (err, data) => {
2 if (err) return console.error('Read failed:', err);
3 console.log('Config:', JSON.parse(data));
4});

3. Modern Promises API (node:fs/promises) - RECOMMENDED STANDARD

Clean, modern, fully non-blocking, and seamlessly integrated with async / await:

1import fs from 'node:fs/promises';
2import path from 'node:path';
3 
4async function manageUserData(user) {
5 const filePath = path.join(process.cwd(), 'data', `user-${user.id}.json`);
6 
7 // 1. Write file with pretty-printed JSON
8 await fs.writeFile(filePath, JSON.stringify(user, null, 2), 'utf8');
9 
10 // 2. Read file back
11 const rawData = await fs.readFile(filePath, 'utf8');
12 const parsedUser = JSON.parse(rawData);
13 
14 // 3. Append to activity log
15 await fs.appendFile(
16 path.join(process.cwd(), 'data', 'activity.log'),
17 `[${new Date().toISOString()}] User ${user.id} updated\n`
18 );
19 
20 return parsedUser;
21}

2. Directory and Metadata Operations

Node.js offers complete control over file system trees and permissions:

1import fs from 'node:fs/promises';
2 
3async function fileOperationsDemo() {
4 // Check if directory exists; create recursively if missing
5 await fs.mkdir('./uploads/avatars', { recursive: true });
6 
7 // Inspect file metadata (size, creation time, permissions)
8 const stats = await fs.stat('./package.json');
9 console.log('File size in bytes:', stats.size);
10 console.log('Is directory?', stats.isDirectory());
11 console.log('Last modified:', stats.mtime);
12 
13 // Read all files in a directory
14 const files = await fs.readdir('./src');
15 console.log('Source files:', files);
16 
17 // Safely delete a file
18 await fs.unlink('./temp.txt').catch(err => {
19 if (err.code !== 'ENOENT') throw err; // Ignore if file already doesn't exist
20 });
21}

Interactive Quiz• Knowledge Check

Multiple Choice Questions

Question 1
Which Node.js file system API is the modern industry standard for use with async/await?
Question 2
Why is using synchronous methods like fs.readFileSync() considered a critical anti-pattern inside an Express.js route handler?
Question 3
How do you create nested directories (e.g., uploads/2026/invoices) without throwing an error if intermediate parent directories do not exist?
Question 4
What does the fs.stat() method return?
Question 5
Which method from fs/promises deletes a file from the file system?

Next Lesson

EventEmitter Pattern & Custom Event Architecture

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
CommonJS vs ES Modules & Package.json Dependency ManagementEventEmitter Pattern & Custom Event Architecture

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master Node.js & Express.js with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext