Skip to content

Commit

Permalink
add: non blocking io
Browse files Browse the repository at this point in the history
  • Loading branch information
thutasann committed Nov 6, 2024
1 parent 1fca1a5 commit 246a582
Show file tree
Hide file tree
Showing 5 changed files with 98 additions and 0 deletions.
58 changes: 58 additions & 0 deletions node-concepts/src/js-general/non-blocking-io/async-sync.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
const fs = require('fs');
const path = require('path');

/** @internal */
function syncFunction() {
console.log('Synchronous function is executed!');
}

// Asynchronous function outside main
async function outsideAsyncFunction() {
console.log('Outside async function started. ===> 2️⃣');
await delay(1000); // Simulate some async work
console.log('Outside async function finished after 1 second. 2️⃣');
}
// Asynchronous function that reads a file
async function readFileAsync(filePath) {
return new Promise((resolve, reject) => {
fs.readFile(filePath, 'utf8', (err, data) => {
if (err) {
reject(err);
} else {
resolve(data);
}
});
});
}

async function delay(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}

/**
* ## Main
* - The await inside the main function does not block functions outside of main.
* - It only pauses the execution of the main function itself until the promise resolves,
* - but it does not block the entire Node.js event loop.
*/
async function main() {
console.log('Main function started. ==> 1️⃣');

console.log('Before file read... 1️⃣');
try {
const fileContent = await readFileAsync('file1.txt');
console.log('File Content: Finished... 1️⃣');
} catch (err) {
console.error('Error reading file:', err);
}

console.log('Waiting for 2 seconds... 1️⃣');
await delay(2000);
console.log('2 seconds passed. 1️⃣');

console.log('Main function finished. ==> 1️⃣');
}

main();

outsideAsyncFunction();
19 changes: 19 additions & 0 deletions node-concepts/src/js-general/non-blocking-io/file-read.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
const fs = require('fs');

fs.readFile('file1.txt', 'utf8', (err, data1) => {
if (err) {
console.error('Error reading file1:', err);
return;
}
console.log('File1 content:', data1);
});

fs.readFile('file2.txt', 'utf8', (err, data2) => {
if (err) {
console.error('Error reading file2:', err);
return;
}
console.log('File2 content:', data2);
});

console.log('Files are being read concurrently.');
Loading

0 comments on commit 246a582

Please sign in to comment.