forked from mbostock/ndjson-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathndjson-join
executable file
·87 lines (79 loc) · 2.41 KB
/
ndjson-join
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
#!/usr/bin/env node
var fs = require("fs"),
readline = require("readline"),
vm = require("vm"),
commander = require("commander"),
requires = require("./requires"),
expression = require("./expression"),
output = require("./output");
commander
.version(require("./package.json").version)
.usage("[options] [expression₀ [expression₁]] <file₀> <file₁>")
.description("Join two newline-delimited JSON streams into a stream of pairs.")
.option("-r, --require <name=module>", "require a module", requires, {d: undefined, i: -1})
.parse(process.argv);
if (commander.args.length < 2 || commander.args.length > 4) {
commander.outputHelp();
process.exit(1);
}
if (commander.args.length < 4) {
if (commander.args.length < 3) commander.args.splice(0, 0, "i");
commander.args.splice(1, 0, commander.args[0]);
}
var i0 = -1,
i1 = -1,
ii = 0,
sandbox = commander.require,
map = new Map,
key0 = expression(commander.args[0]),
key1 = expression(commander.args[1]),
context = new vm.createContext(sandbox);
readline.createInterface({
input: commander.args[2] === "-" ? process.stdin : fs.createReadStream(commander.args[2]),
output: null
}).on("line", function(line) {
sandbox.i = ++i0;
try {
sandbox.d = JSON.parse(line);
} catch (error) {
console.error("stdin:" + (i0 + 1));
console.error(line);
console.error("^");
console.error("SyntaxError: " + error.message);
process.exit(1);
}
var k = key0.runInContext(context);
if (map.has(k)) map.get(k)[0].push(sandbox.d);
else map.set(k, [[sandbox.d], []]);
}).on("close", function() {
if ((ii |= 1) === 3) join();
});
readline.createInterface({
input: commander.args[3] === "-" ? process.stdin : fs.createReadStream(commander.args[3]),
output: null
}).on("line", function(line) {
sandbox.i = ++i1;
try {
sandbox.d = JSON.parse(line);
} catch (error) {
console.error("stdin:" + (i1 + 1));
console.error(line);
console.error("^");
console.error("SyntaxError: " + error.message);
process.exit(1);
}
var k = key1.runInContext(context);
if (map.has(k)) map.get(k)[1].push(sandbox.d);
else map.set(k, [[], [sandbox.d]]);
}).on("close", function() {
if ((ii |= 2) === 3) join();
});
function join() {
map.forEach(function(value, key) {
value[0].forEach(function(v0) {
value[1].forEach(function(v1) {
output([v0, v1]);
});
});
});
}