| 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 | const defaultOutDelimiter = progname.slice(-3) === "tsv" ? "\t" : ",";
|
|---|
| 15 |
|
|---|
| 16 | const options = program
|
|---|
| 17 | .version(JSON.parse(readFileSync(resolve(dirname(fileURLToPath(import.meta.url)), "../package.json"))).version)
|
|---|
| 18 | .usage("[options] [file]")
|
|---|
| 19 | .option("-o, --out <file>", "output file name; defaults to “-” for stdout", "-")
|
|---|
| 20 | .option("-r, --input-delimiter <character>", "input delimiter character", defaultInDelimiter)
|
|---|
| 21 | .option("-w, --output-delimiter <character>", "output delimiter character", defaultOutDelimiter)
|
|---|
| 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 | const outFormat = dsvFormat(options.outputDelimiter);
|
|---|
| 29 |
|
|---|
| 30 | rw.dash.readFile(program.args[0] || "-", (error, text) => {
|
|---|
| 31 | if (error) throw error;
|
|---|
| 32 | rw.dash.writeFile("-", iconv.encode(outFormat.format(inFormat.parse(iconv.decode(text, options.inputEncoding))) + EOL, options.outputEncoding), (error) => {
|
|---|
| 33 | if (error) throw error;
|
|---|
| 34 | });
|
|---|
| 35 | });
|
|---|