| 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]), |
| ); |
| } |
|
|