【发布时间】:2025-11-23 12:20:07
【问题描述】:
我有以下非常简单的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 尝试读取它时,它返回一个空字符串,因为它已被锁定。
关于如何在几次尝试后不崩溃的情况下完成这项工作的任何想法?
谢谢!
【问题讨论】:
-
可以发
/profiles/bill-gates.json的内容吗?首先,删除其中的所有内容,然后重新运行,然后发布内容。
标签: javascript node.js npm fs-extra chokidar