java - 查看更改时出现错误 JSON 输入意外结束

标签 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
})

最佳答案

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

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

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

您也可以对检测进行“去抖动”处理。 more info on that here

fs.watch() 以及 fs.watchFile() 可能会因为操作系统构成​​正确文件更改的方式不同而难以使用。

关于java - 查看更改时出现错误 JSON 输入意外结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54542521/

相关文章:

node.js - 我可以动态地将索引添加到 Mongoose 中的架构中吗?

c# - 仅将对象转换为 JSON 字符串序列化字段

javascript - 如何将循环中的多个变量传递到 ajax json 数据中。

java - 无需重新启动即可生成 Java 线程转储。

java - java中是否有任何函数可以在索引 i 和索引 j (两者都包含)之间的数组中执行循环左移

java - 将图像渲染到标签中

node.js - 如何获取水线记录的模型名称或模型类?

node.js - 除了关联表的对象之外,Sequelizejs 还返回 id

ios - RestKit 0.20嵌套对象映射(对象树的路径不同)

java - 返回客户端时 CXF WS 调度失败