File size: 1,336 Bytes
10695bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { readFile, writeFile } from 'node:fs/promises';
import { TextDecoder } from 'node:util';
import iconv from 'iconv-lite';
import { decodeBuffer, encodeBuffer, UTF8_BOM } from './codec.js';

const SOURCE_ENCODINGS = new Set(['utf8', 'utf-8', 'gbk', 'gb2312', 'cp1252', 'latin1']);

export function decodeSource(buffer, encoding = 'utf8') {
  const normalized = encoding.toLowerCase();
  if (!SOURCE_ENCODINGS.has(normalized)) {
    throw new TypeError(`Unsupported source encoding: ${encoding}`);
  }

  if (normalized === 'utf8' || normalized === 'utf-8') {
    const hasBom = buffer.subarray(0, 3).equals(UTF8_BOM);
    return new TextDecoder('utf-8', { fatal: true }).decode(hasBom ? buffer.subarray(3) : buffer);
  }

  return iconv.decode(buffer, normalized);
}

export async function encodeFile(inputPath, outputPath, options = {}) {
  const input = await readFile(inputPath);
  const text = decodeSource(input, options.sourceEncoding);
  await writeFile(outputPath, encodeBuffer(text, options));
}

export async function decodeFile(inputPath, outputPath, options = {}) {
  const input = await readFile(inputPath);
  const text = decodeBuffer(input, options);
  const output = Buffer.from(text, 'utf8');
  await writeFile(
    outputPath,
    options.outputBom === false ? output : Buffer.concat([UTF8_BOM, output]),
  );
}