我想实现如何使用Node.js一个文件系统观察,使其手表更改特定的JSON文件。
然后,我想获得的文件里面有什么改变。
这里有一种方法:
下面是一个例子:
const fs = require('fs')
const diff = require('deep-diff')
const filepath = './foo.json'
const getCurrent = () => JSON.parse(fs.readFileSync(filepath, {
encoding: 'utf8'
}))
let currObj = getCurrent()
fs.watch(filepath, { encoding: 'buffer' }, (eventType, filename) => {
if (eventType !== 'change') return
const newObj = getCurrent()
const differences = diff(currObj, newObj)
console.log(differences)
// { kind: 'N' } for new key additions
// { kind: 'E' } for edits
// { kind: 'D' } for deletions
currObj = newObj
})
请注意,我用fs.readFileSync
这里赘述。您应该关闭使用fs.readFile
反而是无阻塞更好。