java - 错误查看更改时 JSON 输入意外结束
问题描述
所以我要做的是获取 JSON 文件中已修改的内容及其确切路径。问题是,该 JSON 文件正在被另一个程序修改。每次我运行我的第二个程序来修改我的 JSON 文件时,我都会收到以下错误。有人知道为什么会发生这种情况并有解决办法吗?(此错误仅在使用修改 JSON 文件的程序时打印。我还可以告诉您,修改器程序工作得很好。)
SyntaxError: Unexpected end of JSON input
at JSON.parse (<anonymous>)
at getCurrent (E:\letssee2\app\testor.js:5:31)
at FSWatcher.fs.watch (E:\letssee2\app\testor.js:11:20)
at emitTwo (events.js:126:13)
at FSWatcher.emit (events.js:214:7)
at FSEvent.FSWatcher._handle.onchange (fs.js:1364:12)
我有以下内容:
const fs = require('fs')
const diff = require('deep-diff')
const filepath = '../temp/listings2.json' // File to watch
const getCurrent = () => JSON.parse(fs.readFileSync(filepath, {}))
let currObj = getCurrent()
fs.watch(filepath, {}, (eventType, filename) => {
const newObj = getCurrent()
const differences = diff(currObj, newObj)
var listings2 = JSON.parse(fs.readFileSync("../temp/listings2.json"))
if (differences == undefined) {
return;
}
console.log(JSON.stringify(differences[0]["path"][0]))
console.log(JSON.stringify(differences[0]["path"][1]))
console.log(JSON.stringify(differences[0]["path"][2]))
console.log(JSON.stringify(differences[0]["path"][3]))
var path1 = String(differences[0]["path"][1])
//console.log(`\n\n${path1}\n\n`)
var fullpath = `${String(differences[0]["path"][0])}.${String(differences[0]["path"][1])}.${String(differences[0]["path"][2])}.${String(differences[0]["path"][3])}`
console.log(fullpath)
console.log(listings2[(differences[0]["path"][0])][differences[0]["path"][1]][differences[0]["path"][2]][differences[0]["path"][3]])
currObj = newObj
})
解决方案
假设第二个程序正在正确写入文件:
是否有可能在修改期间而不是在第二个程序完成写入文件之后触发修改事件?
如果是这种情况,您可以懒惰并忽略错误并等待适当的修改完成,只要您绝对确定其他程序将正确修改文件。
或者
您也可以对检测进行“去弹跳”。更多信息在这里
fs.watch()
而且fs.watchFile()
由于操作系统构成正确文件更改的不同方式,因此使用起来可能会很容易受到影响。
推荐阅读
- laravel - 条件组件变量值递增Vue/Laravel
- python-3.x - 如何断言在 pytest 中调用了猴子补丁?
- llvm - LLVM 适合 createBranchWeights() 的参数
- angular - 有没有办法在 Angular 项目中设置自定义 svg 图标库而不使用
标签? - javascript - OpenAPI V3 json 对象到 Swagger HTML 对象的 Javascript 转换以通过 jQuery 更新 DIV
- javascript - 我如何在输入字段而不是跨度中获取价格?
- ckeditor5 - CKEditor 5 自定义构建工具栏未显示
- javascript - 使用 Javascript 将跨度更改为输入
- swiftui - 如何通过点击 ForEach 中的按钮导航到不同的屏幕/视图
- python - python根据循环中的其他2列计算新列值