因此,我要做的是获取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
})发布于 2019-02-05 20:42:12
假设第二个程序正确地写入了文件:
修改事件是否可能是在修改期间触发的,而不是在第二个程序编写完文件之后触发的呢?
如果是这样的话,您可以懒散地忽略错误,并等待适当的修改完成,只要您绝对确信其他程序将正确地修改文件。
或
你也可以进行“去弹跳”探测。这里有更多关于这个的信息
fs.watch()和moreso fs.watchFile()可以很好地处理,因为操作系统的文件更改方式不同。
发布于 2019-02-05 20:34:25
您应该开始调试,只需打印或回显JSON文件,并在解析命令之前查找任何错误。如果你想让我看一下的话,把文件内容贴出来
https://stackoverflow.com/questions/54542521
复制相似问题