所以我想做的是获取 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
})
最佳答案
假设第二个程序正确写入文件:
是否有可能在修改过程中触发修改事件,而不是在第二个程序完成写入文件之后触发?
如果是这种情况,只要您绝对确定其他程序将正确修改文件,您就可以偷懒并忽略错误并等待正确的修改完成。
或
您也可以对检测进行“去抖动”处理。 more info on that here
fs.watch()
以及 fs.watchFile()
可能会因为操作系统构成正确文件更改的方式不同而难以使用。
关于java - 查看更改时出现错误 JSON 输入意外结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54542521/