Bhumi Singhal Bhumi Singhal - 20 days ago 8
Javascript Question

nodejs : syncronise pieces of code

I am deleting somefiles using fs.unlink and then I want to run some code. Due to the async nature of JS what is happening is that my code after unlinking is called before the callback of unlink. How can i Syncronise this? Is promises the only way ?

fs.unlink("FileName",function(err){
console.log("RUN");
})

for(let i = 0; i<10;i++) {
console.log(i);
}


RESULT :

1
2
3
4
5
6
7
8
9
RUN


The problem with using promises is that : If i have many files to delete, then i will have maintain a count of the promises and then check how many have been resolved. This i want to avoid

Answer Source

In this situation, you can use fs.unlinkSync, the synchronous version of fs.unlink:

try {
  fs.unlinkSync("FileName");
  console.log('Removing file successful!');
} catch(e) {
  // TODO: handle errors here
};

console.log("RUN");

for(let i = 0; i<10;i++) {
   console.log(i);
}

As @Keith rightfully mentions in the comments: synchronous operations like this should be use sparingly. If you have large numbers of files to delete, it may be better to use the asynchronous fs.unlink() because you can "start" more of those concurrently (tradeoff: start too many and the performance may suffer because of I/O saturation).