简体   繁体   中英

What does it mean to check if a file exists synchronously?

I am trying to understand the fs.statSync command in Node.js. I read at this question Check synchronously if file/directory exists in Node.js that it will check if a file exists synchronously. I don't understand what this means, whats the difference between checking if it exists synchronously and checking if it exists asynchronously.

The major difference between synchronous and async is that async doesn't wait. You have to learn how to write code in a whole new way to ensure that things happen in the correct order.

It is worth learning how to do this, but it can be a little brain bending at first.

fs.readFileSync(file); // Stops and waits for completion.
console.log("This will always print after fs.readFileSync.");

fs.readFile(file, function callback(err, data) { // Doesn't stop but will run the callback when it HAS read the file.
  if (err) throw err; // File doesn't exist.
  console.log(data);
});
console.log("This will print before fs.readFile finishes, probably, it might not, but it might, you never quite know.");

Synchronously means your code waits until it gets a result. Nothing else happens in your thread until you get that result from fs.statSync() . None of your other code runs. You basically have the program locked up.

Asynchronously means the function returns right away and your code can continue running, but you don't know what the result is right away. Instead, the result is given to you in a callback function that is fired later.

Synchronously means your thread will block while waiting for the file system to find out if the file exists or not.

If you do this asynchronously, you would still ask the file system but the file system would be able to do this in the background, allowing your thread to continue running. Once the file system knows if the file exists or not, it would probably call a callback function in your code to notify you of this, or notify you in some other way without blocking your thread of execution.

这意味着在操作期间,当前“线程”的执行将冻结。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM