---- AI试用 ---域名问题某些图片和js资源无法访问,导致一些代码实例无法运行!(代码里gzui.net换成momen.vip即可)

node将txt文件格式转为utf8

前端开发 蚂蚁 918℃ 0评论
const fs = require('fs').promises;
const path = require('path');
const jschardet = require('jschardet');
const iconv = require('iconv-lite');

// 指定需要处理的文件夹路径
const folderPath = './book';

// 递归遍历文件夹
async function processFolder(folderPath) {
  try {
    const files = await fs.readdir(folderPath);
    await Promise.all(files.map(async (file) => {
      const filePath = path.join(folderPath, file);
      const stat = await fs.stat(filePath);

      if (stat.isFile()) {
        // 处理文件
        await processFile(filePath);
      } else if (stat.isDirectory()) {
        // 递归处理子文件夹
        await processFolder(filePath);
      }
    }));
  } catch (err) {
    console.error('处理文件夹时发生错误:', err);
  }
}

// 处理文件
async function processFile(filePath) {
  const extname = path.extname(filePath);
  if (extname !== '.txt') {
    console.log(filePath, '不是txt文件,跳过编码转换');
    return;
  }

  try {
    const data = await fs.readFile(filePath);

    // 检测文件编码
    const detectedEncoding = jschardet.detect(data).encoding;

    // 判断文件是否为UTF-8编码
    if (detectedEncoding.toLowerCase() === 'utf-8') {
      console.log(filePath, '已经是UTF-8编码');
      return;
    }

    // 将文件内容从原编码转换为UTF-8
    const content = iconv.decode(data, detectedEncoding);
    const utf8Content = iconv.encode(content, 'utf-8');

    // 将转换后的内容写入文件
    await fs.writeFile(filePath, utf8Content);
    console.log(filePath, '编码修改为UTF-8成功');
  } catch (err) {
    console.error('处理文件时发生错误:', err);
  }
}

// 处理指定的文件夹
processFolder(folderPath);

转载请注明:有爱前端 » node将txt文件格式转为utf8

喜欢 (2)or分享 (0)