-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
32 lines (28 loc) · 909 Bytes
/
index.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
const { watchFile, createReadStream } = require('fs')
const objKey = (obj) => Object.keys(obj)[0]
const objValue = (obj) => Object.values(obj)[0]
const readFile = ({ file, start, end }) =>
new Promise((resolve, reject) => {
const stream = createReadStream(file, { start, end })
stream.on('data', resolve)
stream.on('end', () => stream.destroy())
stream.on('error', err => reject(err) || stream.destroy())
})
const fsWatchStream = (files, cb) =>
files.forEach(file =>
watchFile(objValue(file), ({ size: currSize }, { size: prevSize }) =>
readFile({
file: objValue(file),
start: currSize - (currSize - prevSize),
end: currSize
})
.then((data) =>
cb(null, JSON.stringify({
file: objKey(file),
data: data.toString()
})))
.catch(err =>
cb(err, null))
)
)
module.exports = fsWatchStream