| 1 | #!/usr/bin/env node
|
|---|
| 2 |
|
|---|
| 3 | import {EOL} from "os";
|
|---|
| 4 | import {basename, dirname, resolve} from "path";
|
|---|
| 5 | import {readFileSync} from "fs";
|
|---|
| 6 | import {fileURLToPath} from "url";
|
|---|
| 7 | import rw from "rw";
|
|---|
| 8 | import {program} from "commander";
|
|---|
| 9 | import iconv from "iconv-lite";
|
|---|
| 10 | import {dsvFormat} from "../src/index.js";
|
|---|
| 11 |
|
|---|
| 12 | const progname = basename(process.argv[1]);
|
|---|
| 13 | const defaultInDelimiter = progname.slice(0, 3) === "tsv" ? "\t" : ",";
|
|---|
| 14 |
|
|---|
| 15 | const options = program
|
|---|
| 16 | .version(JSON.parse(readFileSync(resolve(dirname(fileURLToPath(import.meta.url)), "../package.json"))).version)
|
|---|
| 17 | .usage("[options] [file]")
|
|---|
| 18 | .option("-o, --out <file>", "output file name; defaults to “-” for stdout", "-")
|
|---|
| 19 | .option("-r, --input-delimiter <character>", "input delimiter character", defaultInDelimiter)
|
|---|
| 20 | .option("-a, --auto-type", "parse rows with type inference (see d3.autoType)")
|
|---|
| 21 | .option("-n, --newline-delimited", "output newline-delimited JSON")
|
|---|
| 22 | .option("--input-encoding <encoding>", "input character encoding; defaults to “utf8”", "utf8")
|
|---|
| 23 | .option("--output-encoding <encoding>", "output character encoding; defaults to “utf8”", "utf8")
|
|---|
| 24 | .parse(process.argv)
|
|---|
| 25 | .opts();
|
|---|
| 26 |
|
|---|
| 27 | const inFormat = dsvFormat(options.inputDelimiter);
|
|---|
| 28 |
|
|---|
| 29 | rw.dash.readFile(program.args[0] || "-", (error, text) => {
|
|---|
| 30 | if (error) throw error;
|
|---|
| 31 | const rowConverter = options.autoType ? dsv.autoType : null
|
|---|
| 32 | const rows = inFormat.parse(iconv.decode(text, options.inputEncoding), rowConverter);
|
|---|
| 33 | rw.dash.writeFile(options.out, iconv.encode(options.newlineDelimited
|
|---|
| 34 | ? rows.map((row) => JSON.stringify(row)).join("\n") + "\n"
|
|---|
| 35 | : JSON.stringify(rows) + EOL, options.outputEncoding), (error) => {
|
|---|
| 36 | if (error) throw error;
|
|---|
| 37 | });
|
|---|
| 38 | });
|
|---|