我有以下非常简单的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"
}
顺便说一句,如果我从正常状态更改CRLF
为LF
正常状态,我可以在它崩溃之前再做一些修改。
我的印象是,出于某种原因,文件:/profiles/bill-gates.json
在某个时候被锁定,当Node
尝试读取它时,它返回一个空字符串,因为它被锁定了。
任何关于如何使这项工作在几次尝试后不会崩溃的想法?
谢谢!