Thank you, great one 💙
But I have a little question..
What's the difference between fs.readFile and fs.Promises.readFile , in other words where will be fs.Promises.readFile priority in the context of this post
Since, promises come under microtasks, as far as my knowledge, fs.Promises.readFile gets the priority but the only catch is that the handler passed to .then(fn) i.e fn here is pushed to the queue (registered) only after the promise is resolved/rejected.
Whereas, if it is a fs.readFile, its callback is immediately registered by the event loop when it(the event loop) encounters the fs.readFile operation.
Thus, if you do something like:
fs.promises.readFile(`./file.txt`).then((buff) => {
console.log(`> resolved promise`);
});
fs.readFile(`./file.txt`, (err, buff) => {
if (err) throw err;
console.log(`> not a promise`);
});
Thank you for replying 💙 , but for this piece of code I put fs.promise.readFile upfront so it would(should) be resolved and pushed to the queue early before settimeout, can you clarify why this output .. !
const fs=require('fs')
// text.txt file just contains 'Hello World'
const read=fs.promises.readFile('./text.txt','utf-8')
read.then(()=>{
console.log('from promise')
})
//just looping to ensure that the file has finished reading
for(let i=0;i<10000;i++){
console.log('looping...')
}
setTimeout(() => {
console.log('from setTimeout')
}, 0);
//--output--
// looping...
// from setTimeout
// from promise
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Thank you, great one 💙
But I have a little question..
What's the difference between fs.readFile and fs.Promises.readFile , in other words where will be fs.Promises.readFile priority in the context of this post
Since, promises come under microtasks, as far as my knowledge,
fs.Promises.readFile
gets the priority but the only catch is that the handler passed to.then(fn)
i.e fn here is pushed to the queue (registered) only after the promise is resolved/rejected.Whereas, if it is a
fs.readFile
, its callback is immediately registered by the event loop when it(the event loop) encounters thefs.readFile
operation.Thus, if you do something like:
You may see that the output will be:
Hope this helps!
Thank you for replying 💙 , but for this piece of code I put fs.promise.readFile upfront so it would(should) be resolved and pushed to the queue early before settimeout, can you clarify why this output .. !