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

标签 javascript node.js fs

我试图理解 Node.js 中的 fs.statSync 命令。我读过这个问题Check synchronously if file/directory exists in Node.js它将检查文件是否同步存在。我不明白这是什么意思,检查它是否同步存在和检查它是否异步存在有什么区别。

最佳答案

同步和异步之间的主要区别是异步不等待。您必须学习如何以全新的方式编写代码,以确保事情按正确的顺序发生。

值得学习如何做到这一点,但一开始可能会有点费脑子。

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.");

关于javascript - 检查文件是否同步存在是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31433251/

相关文章:

javascript - 适用于 Wrike API v3 的 Ajax/ASP.net Oauth2

通过 DOM 设置 Javascript 函数参数

javascript - 发布到服务器端代码内的路由

node.js - Emacs Node REPL 奇怪的行为

javascript - 动态设置参数时如何解决路径问题?

javascript - 如何在nodejs中使用fs从多个目录获取文件名?

javascript - 弹出数组元素,将其拆分并保存到不同的数组中

javascript - “Text on the canvas movable by dragging text to their desired position?”

node.js - NodeJs - 使用 redis,用 express 连接 redis

javascript - 如何使用 fast-csv npm 将新行或新行处的数据(新行)附加到现有 csv 文件