简体   繁体   English

检查文件是否同步存在是什么意思?

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

I am trying to understand the fs.statSync command in Node.js. 我正在尝试了解Node.js中的fs.statSync命令。 I read at this question Check synchronously if file/directory exists in Node.js that it will check if a file exists synchronously. 我读过这个问题,在Node.js同步检查文件/目录是否存在 ,它将检查文件是否同步存在。 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() . 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. 一旦文件系统知道文件是否存在,它可能会在您的代码中调用一个回调函数来通知您此消息,或者以其他方式通知您而不会阻塞您的执行线程。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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