Experiment #2 · Node.js Lab
Synchronous vs Asynchronous File Operations in Node.js
Explore how Node.js handles file reads with the built-in fs module — comparing fs.readFileSync() and fs.readFile() to see the difference in execution order and blocking behavior.
Aim
The objective of the project is to create a basic Node.js program that compares synchronous and asynchronous file operations with the help of the File System (fs) module.
Software Requirements
Windows 10/11
Node.js
NPM
Visual Studio Code
Source Code
step 1Create a project folder
mkdir NodeDemo
cd NodeDemo
step 2Create a file named test.txt
test.txt
Hello Node.js
step 3Create a file named Source.js
Source.js
const fs = require("fs");
console.log(fs.readFileSync("test.txt", "utf8"));
fs.readFile("test.txt", "utf8", (err, data) => console.log(data));
console.log("Done");
step 4Run the program
node Source.js
Output
Console
Hello Node.js
Done
Hello Node.jsTerminal Output
Terminal
C:\NodeDemo> node Source.js
Hello Node.js
Done
Hello Node.jsResult: The Node.js program was executed successfully, and the difference between synchronous and asynchronous file operations was demonstrated — readFileSync() blocks and runs first, while readFile() runs in the background and completes after the synchronous code finishes.






tq sir
ReplyDeleteIf you like our Content please Share, Follow our posts and Blog. Thank you.
ReplyDelete