-
Notifications
You must be signed in to change notification settings - Fork 4
/
push.js
executable file
·93 lines (72 loc) · 1.7 KB
/
push.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#!/usr/bin/env node
// remonit-push: cli command to push data from stdin to Remonit stats object
// Usage: remonit-push <stats_name>
// Example: ls | remonit-push 'my ls output'
// Noitce: login info should be stored in either ./remonit.json or
// ~/.remonit.json
'use strict'
var stats = {}
var name = process.argv[2]
var CHARS_MAX = 5000
if (!name) {
console.log('Usage: remonit-push <stats_name>\n')
return
}
var _ = require('lodash')
var remonit = require('./remonit.js')
console.log('Login to Remonit server...')
remonit.connect(function(err) {
if (err) {
console.log(err + '\n')
return
}
console.log('Logged in.')
init()
})
function init() {
remonit.get('stats', function(err, result) {
if (err) {
console.log(err + '\n')
remonit.close()
return
}
var s = result[0]
stats = {_id: s._id, userId: s.userId} // we only need these to update stats
stats[name] = s[name] || '' // current stats value
run()
})
}
var ended = false
function run() {
var stdin = process.stdin
stdin.on('data', function(chunk) {
write(chunk.toString())
})
stdin.on('end', function() {
finalize()
})
console.log('Piping to Remonit...\n')
stdin.resume()
}
// throttled update
var updateStats = _.throttle(function() {
if (!ended) remonit.put('stats', stats)
}, 1000)
function write(data) {
// echo
process.stdout.write(data)
// truncate and update stats
stats[name] += data
if (stats[name].length > 2 * CHARS_MAX) {
stats[name] = stats[name].substr(-CHARS_MAX)
}
updateStats()
}
function finalize() {
// prevent other updates
ended = true
// update one last time
remonit.put('stats', stats, function() {
remonit.close()
})
}