forked from tmcw/togeojson-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
executable file
·61 lines (54 loc) · 1.5 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
60
61
#!/usr/bin/env node
const tj = require("@tmcw/togeojson");
const argv = require("minimist")(process.argv.slice(2));
const fs = require("fs");
const { DOMParser } = require("xmldom");
function* convert(data) {
const snippet = data.substring(0, 200);
const parser = new DOMParser();
if (snippet.includes("<kml")) {
yield* tj.kmlGen(parser.parseFromString(data));
} else if (snippet.includes("<gpx")) {
yield* tj.gpxGen(parser.parseFromString(data));
} else {
throw new Error("Could not detect file format of an input");
}
}
if (process.stdin.isTTY && !argv._.length) {
console.error(`Usage:
togeojson FILE
togeojson < FILE
togeojson FILE1 FILE2 FILE3…`);
} else if (argv._.length) {
process.stdout.write('{\n "type": "FeatureCollection",\n "features": [\n');
let first = true;
for (let file of argv._) {
for (let feature of convert(fs.readFileSync(file, "latin1"))) {
if (!first) {
process.stdout.write(",\n ");
} else {
process.stdout.write(" ");
first = false;
}
process.stdout.write(JSON.stringify(feature));
}
}
process.stdout.write("\n ]\n}\n");
} else {
let data = "";
process.stdin.setEncoding("latin1");
process.stdin.on("readable", () => {
let chunk;
while ((chunk = process.stdin.read())) {
data += chunk;
}
});
process.stdin.on("end", () => {
console.log(
JSON.stringify({
type: "FeatureCollection",
features: Array.from(convert(data)),
})
);
});
}