javascript - 从 chokidar.watch(path_file).on ('change' 内的 fs.readFile 获取空字符串,...)

标签 javascript node.js npm fs-extra chokidar

我有以下非常简单的Node项目:

https://github.com/tlg-265/chokidar-issue

enter image description here

$ git clone https://github.com/tlg-265/chokidar-issue
$ cd chokidar-issue
$ npm i
$ npm run watch-changes

它基本上负责检测文件的更改:

/profiles/bill-gates.json

然后执行一个操作。

为了做到这一点,我有以下文件:

/profile-watcher.js

const fs = require('fs-extra');
const colors = require('colors/safe');
const chokidar = require('chokidar');

const path_file = `profiles/bill-gates.json`;
console.log(`Current Profile: ${colors.red.bgBrightYellow(path_file)}`);

let profile_before = {};

chokidar.watch(path_file).on('change', async (path) => {

  console.log();
  console.log(`${colors.blue.bgYellow(`->`)} Profile changed: ${path}`);

  fs.readFile(path, (err, profile_json) => {
    console.log(`->${profile_json}<-`);
    let profile = JSON.parse(profile_json);
    if (JSON.stringify(profile) != JSON.stringify(profile_before)) {
      console.log('The profile has changed.');
      profile_before = profile;
    }
  });

});

当我运行项目时:

$ npm run watch-changes

并对文件进行以下修改:/profiles/bill-gates.json

  • 修改 1:比尔盖茨 -> 比尔盖茨 ABC
  • 修改 2:比尔盖茨 ABC -> 比尔盖茨 ABC DEF

它工作正常,将该文件的内容输出到控制台。

但是当我进行下一次修改时:

  • 修改 3:比尔盖茨 ABC -> 比尔盖茨 ABC DEF GHI

然后我收到以下错误:

-> Profile changed: profiles\bill-gates.json
-><-
undefined:1

SyntaxError: Unexpected end of JSON input
    at JSON.parse (<anonymous>)
    at fs.readFile (\chokidar-issue\profile-watcher.js:17:24)
    at \chokidar-issue\node_modules\graceful-fs\graceful-fs.js:115:16
    at FSReqWrap.readFileAfterClose [as oncomplete] (internal/fs/read_file_context.js:53:3)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! chokidar-issue@1.0.0 watch-changes: `node profile-watcher.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the chokidar-issue@1.0.0 watch-changes script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Roaming\npm-cache\_logs\2020-02-28T23_44_01_038Z-debug.log

/profiles/bill-gates.json(标志:UTF-8/CRLF)

{
  "name": "Bill Gates",
  "email": "bill.gates@microsoft.com",
  "password": "windows",
  "country": "USA"
}

顺便说一句,如果我从 CRLF 更改为 LF 通常我可以在崩溃之前做一些修改。

我的印象是,由于某些原因,文件:/profiles/bill-gates.json在某个时候被锁定,当Node尝试读取它时它返回一个空字符串,因为它被锁定。

有什么想法可以让这项工作在尝试几次后不会崩溃吗?

谢谢!

最佳答案

我也遇到了和你一样的问题

“chokidar”中有一个选项,您可以在其中awaitWriteFinish。它是基于时间的,并检查文件的大小是否发生变化。如果没有,那么它将调用回调。

const watcher = chokidar.watch(configPathString, { 
    persistent: true,
    awaitWriteFinish: {
        stabilityThreshold: 500
    } 
});
watcher.on('change', (path, stats) => {

    fs.readFile(configPathString,(err, data)=>{
        if (err) throw err;
        
        //console.log('data',data);

        let receivedData = JSON.parse(data);

        //Do whatever you like
    })
});

关于javascript - 从 chokidar.watch(path_file).on ('change' 内的 fs.readFile 获取空字符串,...),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60460751/

相关文章:

javascript - 当鼠标放在子级上时取消单击父级

javascript - 在 jQuery 中选择除 ... 之外的所有元素

node.js - 分享 Sequelize 模型的最佳方式

javascript - Musixmatch API 轨道搜索功能

javascript - 如何为 npm 脚本提供默认参数值?

javascript - 如何在 npm 脚本 glob 模式中使用否定?

javascript - 如何将history.pushState与浏览器的后退功能结合使用

javascript - Slider FileReader JS 多图上传(递增索引)

javascript - Nodejs 中如何只选择 10% 的请求?

javascript mysql 和 Promise