node.js - 乔基达尔 : onchange event for a file is possibly triggered to fast

标签 node.js file sublimetext3 onchange is-empty

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

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

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

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

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

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

最佳答案

浏览 performance chokidar 自述文件部分,我发现了以下内容:

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.

这看起来可以解决您的问题,假设文件保存之间的时间间隔超过几秒钟。

关于node.js - 乔基达尔 : onchange event for a file is possibly triggered to fast,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34750158/

相关文章:

javascript - 对 JavaScript/nodejs 中的 'use strict' 感到困惑

sublimetext3 - 删除 Sublime Text 中所有不包含字符串的行

angularjs - Nodejs 中的 req.body 为空 :{}?

node.js - Nginx 与 dockerized NodeJS

c++ - 将有限行数写入文本文件的算法

Java FileOutputStream 设置文件图标

php - 存储敏感数据的最佳方式

python - api : how to get selected text from object sublime. 选择

unicode - Sublime Text 控制台不显示带重音的线条

javascript - Express js 聊天应用程序 :404 error on socket. io.js 文件