-
Notifications
You must be signed in to change notification settings - Fork 0
/
fileWatch.js
49 lines (42 loc) · 1.27 KB
/
fileWatch.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
const watch = require("node-watch")
const fs = require("fs")
const EventEmitter = require("events")
// read function
async function readFileAt(filename,start,length) {
let fd = await fs.promises.open(filename)
let buf = Buffer.alloc(length,0,'utf-8')
await fd.read(buf,0,length,start)
await fd.close()
return buf.toString()
}
class fileWatch extends EventEmitter {
constructor (filepath) {
super()
this.filepath = filepath
}
async watching(evt, name) {
let nowStatus = await fs.promises.stat(this.filepath)
// await readFileAt()
let start = this.lastStatus.size
let diff = nowStatus.size - start
if (nowStatus.size == 0) {
this.emit("reset")
} else if (diff == 0) {
return
} else if (diff > 0) {
this.emit("append",await readFileAt(this.filepath,start,diff))
} else if (diff <0) {
this.emit("remove",-diff)
}
this.lastStatus = nowStatus
}
async start() {
/** @type { import("fs").StatsBase } */
this.lastStatus = await fs.promises.stat(this.filepath)
watch(
this.filepath,{ encoding: "utf-8" },
this.watching.bind(this)
)
}
}
module.exports = fileWatch