首页 > 解决方案 > 错误查看更改时 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
})

标签: javanode.jsjson

解决方案


假设第二个程序正在正确写入文件:

是否有可能在修改期间而不是在第二个程序完成写入文件之后触发修改事件?

如果是这种情况,您可以懒惰并忽略错误并等待适当的修改完成,只要您绝对确定其他程序将正确修改文件。

或者

您也可以对检测进行“去弹跳”。更多信息在这里

fs.watch()而且fs.watchFile()由于操作系统构成​​正确文件更改的不同方式,因此使用起来可能会很容易受到影响。


推荐阅读