Bhumi Singhal Bhumi Singhal - 27 days ago 8
Node.js Question

nodejs : syncronise code execution

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);
}