-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
59 lines (43 loc) · 1.02 KB
/
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
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
var dotpath = require('deep-property')
var concat = require('concat-stream')
var through = require('through2')
var duplex = require('duplexify')
module.exports = cob
function cob (keys) {
var stream = through()
return duplex(concat(onend), stream)
function onend (buf) {
var data = parseJson(buf)
if (!keys) {
print(data)
return stream.push(null)
}
if (typeof keys === 'string') {
keys = [keys]
}
if (Array.isArray(keys)) {
keys.map(lookup).forEach(print)
return stream.push(null)
}
print(Object.keys(keys).reduce(updateObj, data))
stream.push(null)
function lookup (key) {
return dotpath.get(data, key)
}
}
function updateObj (data, key) {
dotpath.set(data, key, keys[key])
return data
}
function print (obj) {
stream.push(JSON.stringify(obj, null, 2) + '\n')
}
function parseJson (str) {
try {
return JSON.parse(str.toString())
} catch (err) {
stream.emit('error', err)
return false
}
}
}