This repository was archived by the owner on Mar 10, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathconvert-encoding.js
More file actions
96 lines (84 loc) · 2.47 KB
/
convert-encoding.js
File metadata and controls
96 lines (84 loc) · 2.47 KB
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
88
89
90
91
92
93
94
95
96
#!/usr/bin/env node
//@ts-check
import iconv from "iconv-lite";
import { parseArgs } from "node:util";
import { existsSync, readFileSync, writeFileSync } from "node:fs";
import { resolve } from "path";
function help() {
console.log(`
=========================================================================================
convert-encoding.js - Converts the encoding of a file
USAGE:
node convert-encoding.js --file <filename> --source-encoding <source-encoding> --target-encoding <target-encoding>
OPTIONS:
--file, -f <filename> Specify the file to convert
--source-encoding, -s <source-encoding> Specify the source encoding
--target-encoding, -t <target-encoding> Specify the target encoding (default: utf-8)
--help, -h Display this help message
`);
process.exit(0);
}
async function main() {
try {
const { values } = parseArgs({
options: {
help: {
type: "boolean",
short: "h",
},
file: {
type: "string",
short: "f",
},
"source-encoding": {
type: "string",
short: "s",
},
"target-encoding": {
type: "string",
short: "t",
default: "utf-8",
},
},
});
// sanity checks
if (values.help) {
help();
}
if (typeof values.file !== "string") {
throw new Error("file must be a string");
}
const filePath = resolve(process.cwd(), values.file);
if (!existsSync(filePath)) {
throw new Error("file does not exist");
}
if (!values["source-encoding"]) {
throw new Error("source-encoding must be a string");
}
if (typeof values["source-encoding"] !== "string") {
throw new Error("source-encoding must be a string");
}
if (typeof values["target-encoding"] !== "string") {
throw new Error("target-encoding must be a string");
}
const sourceEncoding = values["source-encoding"];
const targetEncoding = values["target-encoding"];
const buffer = readFileSync(filePath);
const str = iconv.decode(buffer, sourceEncoding);
const targetFilePath = filePath
.split(".")
.map((e, i, a) => {
if (i === a.length - 1) {
return `${targetEncoding}.${e}`;
}
return `${e}`;
})
.join(".");
writeFileSync(targetFilePath, str);
} catch (error) {
console.error(error.message);
help();
process.exit(1);
}
}
main().catch(console.error);