chokidar:文件的 onchange 事件可能被快速触发

chokidar: onchange event for a file is possibly triggered to fast

我们正在 Ubuntu 服务器上使用 chokidar 和 nodejs 监视文件更改。它工作得很好,但有时我认为我们在更改文件时的保存方式有问题:在 chokidar 中触发了 "onchange" 事件,但是当我们在回调中读取文件时,它是空的或 (很少)没有写完整。我们不知道这是由文本编辑器编写文件、客户端计算机上的操作系统、服务器上的 OS 或文件系统 (ext4) 引起的问题,还是某种错误chokidar.

这个空文件问题现在几乎每次都发生在一台使用 sublime 3 的计算机(mac,最新的 osx 版本)上进行的文件更改。在 sublime 中我们尝试设置“atomic_save”(创建一个临时文件然后覆盖原始文件),但它并没有解决我们的问题:

  1. atomic_save 设置为“false”,文件在 onchange 事件中似乎总是空的,
  2. atomic_save“真”有时是空的,有时是部分写的。

我们之前使用 phpstorm 时遇到过这个问题,但是在切换到 '使用“安全写入”(首先将更改保存到临时文件)' - 所以设置与 atomic_save 在 sublime 中,这也是我们在 sublime 中尝试 atomic_save 的原因 - 写入完成后 onchange 事件被正确触发。

所以我们的问题是,有没有办法在文件以某种方式完全写入时触发“onchange”(在 chokidar 中,在 OS 中,在 sublime 中)?或者我们是否必须在“onchange”事件中检查文件大小,直到一段时间没有改变(不太好)?或者我们的问题可能是由于其他原因导致的?

如有任何提示,我们将不胜感激!提前致谢!

查看 chokidar 自述文件的 performance 部分,我发现了以下内容:

awaitWriteFinish (default: false). By default, the add event will fire when a file first appear on disk, before the entire file has been written. Furthermore, in some cases some change events will be emitted while the file is being written. In some cases, especially when watching for large files there will be a need to wait for the write operation to finish before responding to a file creation or modification. Setting awaitWriteFinish to true (or a truthy value) will poll file size, holding its add and change events until the size does not change for a configurable amount of time. The appropriate duration setting is heavily dependent on the OS and hardware. For accurate detection this parameter should be relatively high, making file watching much less responsive. Use with caution.

  • options.awaitWriteFinish can be set to an object in order to adjust timing params:
    • awaitWriteFinish.stabilityThreshold (default: 2000). Amount of time in milliseconds for a file size to remain constant before emitting its event.
    • awaitWriteFinish.pollInterval (default: 100). File size polling interval.

这看起来可以解决您的问题,前提是文件保存间隔超过几秒。