- Node Cookbook(Third Edition)
- David Mark Clements Matthias Buus Matteo Collina Peter Elger
- 241字
- 2024-10-29 20:27:02
How to do it...
Let's start by loading the dependencies we'll be needing:
const fs = require('fs')
const human = require('human-time')
Next we'll set up some references:
const interval = 5007
const file = process.argv[2]
var exists = false
Do a quick check to make sure we've been supplied a file:
if (!file) {
console.error('supply a file')
process.exit(1)
}
Now we'll set up some utility functions, which will help us interpret the file change event:
const created = ({birthtime}) => {
return !exists && (Date.now() - birthtime) < interval
}
const missing = ({birthtime, mtime, atime, ctime}) => {
return !(birthtime|mtime|atime|ctime)
}
const updated = (cur, prv) => cur.mtime !== prv.mtime
Finally, we use fs.watchFile to poll the specified file and then log out the activity from the listener function supplied to fs.watchFile like so:
fs.watchFile(file, {interval}, (cur, prv) => {
if (missing(cur)) {
const msg = exists ? 'removed' : 'doesn\'t exist'
exists = false
return console.log(`${file} ${msg}`)
}
if (created(cur)) {
exists = true
return console.log(`${file} created ${human((cur.birthtime))}`)
}
exists = true
if (updated(cur, prv)) {
return console.log(`${file} updated ${human((cur.mtime))}`)
}
console.log(`${file} modified ${human((cur.mtime))}`)
})
We should now be able to test our watcher.
In one terminal, we can run the following:
$ node watcher my-file.txt
And in another terminal, we can make a change:
$ echo "more content" >> my-file.txt
Alternatively, we can remove the file:
$ rm my-file.txt
And we can also recreate the file:
$ echo "back again" > my-file.txt
We should be seeing results similar to this:
