-
Notifications
You must be signed in to change notification settings - Fork 5
/
sculpt.js
72 lines (63 loc) · 1.92 KB
/
sculpt.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
'use strict'
const events = require('events')
const fs = require('fs')
const os = require('os')
const path = require('path')
const Parse = require('fast-json-parse')
const defaultOptions = {
path: path.join(os.tmpdir(), 'aborsculpt.json'),
interval: 60000,
loggers: []
}
function changeLevels (loggers, levels) {
const len = (loggers.length === levels.length) ? loggers.length : levels.length
for (let i = 0; i < len; i += 1) {
loggers[i].level = levels[i]
}
}
function Arborsculpt (options) {
if (!(this instanceof Arborsculpt)) return new Arborsculpt(options)
const opts = Object.assign({}, defaultOptions, options)
const resolvedFP = path.resolve(opts.path)
const emitter = this
let mtime
function readFile () {
fs.open(resolvedFP, 'r', function (err, fd) {
if (err) return emitter.emit(err)
fs.readFile(fd, function (err, file) {
if (err) return emitter.emit(err)
const result = new Parse(file)
if (result.err) return emitter.emit(err)
let levels
if (result.value.level) {
levels = new Array(opts.loggers.length)
levels.fill(result.value.level)
} else if (result.value.levels) {
levels = result.value.levels
} else {
return emitter.emit(new Error('cannot find level configuration in file'))
}
try {
changeLevels(opts.loggers, levels)
} catch (e) {
emitter.emit(e)
}
})
})
}
const interval = setInterval(
function arborsculptPoll () {
fs.stat(resolvedFP, function (err, stats) {
if (err) return // either missing or no permissions, so don't care
if (mtime === stats.mtime) return
mtime = stats.mtime
readFile()
})
},
opts.interval
)
interval.unref()
}
Arborsculpt.prototype = Object.create(events.EventEmitter.prototype)
Arborsculpt.constructor = Arborsculpt
module.exports = Arborsculpt