查看更改时,JSON输入的错误意外结束

时间:2019-02-05 20:27:56

标签: java node.js 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
})

2 个答案:

答案 0 :(得分:1)

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

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

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

您还可以进行“反跳”检测。 more info on that here

fs.watch()和更多的fs.watchFile()可能会令人厌烦,因为操作系统构成​​适当文件更改的方式不同。

答案 1 :(得分:0)

您应该通过仅打印或回显JSON文件并在parse命令之前查找任何错误来开始调试。如果您希望我看一下,请发布文件内容

相关问题