Solve a simple JavaScript problem. There is JS code: const fs = require(\'fs\');
ID: 3744417 • Letter: S
Question
Solve a simple JavaScript problem.
There is JS code:
const fs = require('fs');
// async write
fs.writeFile('hello.txt', 'hello from Node! I am here Another line', function(err) {
if(err) {
console.log('-------');
console.log('Error writing to file.');
console.log('-------');
} else {
console.log('-------');
console.log('1. writing to file is successful.');
console.log('-------');
}
}
);
// async write with __dirname
fs.writeFile(__dirname + '/hello1.txt', 'another hello from Node! I am here Another line', function(err) {
if(err) {
console.log('-------');
console.log('Error writing to file.');
console.log('-------');
} else {
console.log('-------');
console.log('2. writing to file is successful.');
console.log('-------');
}
}
);
// sync write
try {
fs.writeFileSync(__dirname + '/hello2.txt', 'hello from Node!');
console.log('-------');
console.log('3. sync write successful');
console.log('-------');
} catch(err) {
console.log('-------');
console.error('Error writing file.');
console.error(err);
console.log('-------');
}
After I run those code, I got the result as follows:
My question is why output is in "3...1....2..." order? Can you explain it carefully?
3. sync write successful 1. writing to file is successful. 2. writing to file is successful.Explanation / Answer
3. sync write is successful is printed first as it is a sync call, and node is single thereaded so its is non blocking call , the the htread to print the line first.
1. Now 1, 2 both goes in event loop stack which is first in and first out algo , so 1. block goes in event loop first when I/O operation done it returns it callback, after that 2. function exexcutes.
So final output is :- 3(Sync non block) , 1(Event loop ,first exctued), 2(Event loop second executed)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.