3

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

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

在此处输入图像描述

$ 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:Bill Gates -> Bill Gates ABC
  • 修改2:Bill Gates ABC -> Bill Gates ABC DEF

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

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

  • 修改3:Bill Gates ABC -> Bill Gates 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"
}

顺便说一句,如果我从正常状态更改CRLFLF正常状态,我可以在它崩溃之前再做一些修改。

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

任何关于如何使这项工作在几次尝试后不会崩溃的想法?

谢谢!

4

3 回答 3

3

我和你有同样的问题。

“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
    })
});
于 2020-11-27T22:48:38.703 回答
0

我可以通过添加一些恢复后备来使其工作:

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

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

let profile_before = fs.readFileSync(path_file).toString();

chokidar.watch(path_file).on('change', async (path_changed) => {
  let profile = fs.readFileSync(path_changed).toString();
  if (IsValidJson(profile)) {
    if (profile != profile_before) {
      console.log();
      console.log(`Profile changed: ${colors.red.bgBrightYellow(path_changed)}`);
      process_profile(profile);
      profile_before = profile;
    }
  }
  else {
    sleep.msleep(100); // this is necessary
  }
});

function process_profile(profile_json) {
  const profile = JSON.parse(profile_json);
  console.log(`${profile_json}`);
  console.log(profile.name);
}

function IsValidJson(str) {
  try {
    JSON.parse(str);
  } catch (e) {
    return false;
  }
  return true;
}

似乎当您保存文件时(至少在 Windows 上),有时会有一段时间(非常短的时间)文件变得清晰,几毫秒后它会得到实际内容。在这两种情况下,on-change事件都会被触发。因此,我们只需要验证文件的内容是否为 JSON。在那种情况下,我只需要忽略它并等待下一个on-change事件。

于 2020-03-01T02:52:44.963 回答
0

这可能是一种竞争条件。像这样使您的 JSON.parse 安全:

const path = require('path')

chokidar.watch(path_file).on('change', async (path) => {
  fs.readFile(path, 'utf8', (err, profile_json) => {
    if (!profile_json) {
      console.log(`${path} is an empty file!`)
      return
    }
    const profile = JSON.parse(profile_json);
    if (JSON.stringify(profile) != JSON.stringify(profile_before)) {
      console.log('The profile has changed.');
      profile_before = profile;
    }
  });

});
于 2020-02-29T11:52:23.933 回答