【前端技巧】多个文件重命名,你还在一个个手动改?

101 阅读1分钟

你还在一个个手动重命名文件吗?

这样不仅效率低下,还特别容易出错。文件一多,光是重复性的修改就能耗费大量时间和精力;更别说一不小心改错了名称或顺序,还得从头检查甚至重新来过,既麻烦又容易影响工作进度。

如果你还没有更高效的解决方案,不妨试试我这个方法,让你轻松批量重命名文件,节省时间,避免出错,实现真正的高效办公!

准备

  1. 先创建一个空文件夹,用vscode打开
  2. 运行
npm install translate-google
  1. 创建一个 index.js文件,写入下面的代码

代码

在index.js中添加以下代码:

const fs = require('fs');
const path = require('path');
const translate = require('translate-google');
const toPinyin = require('chinese-to-pinyin');

const folderPath = './切图';
const folderOut = './输出';

fs.readdir(folderPath, async (err, files) => {
    if (err) {
        console.error('Error reading folder:', err);
        return;
    }

    for (const file of files) {
        try {
            const filePath = path.join(folderPath, file);
            const fileName = path.basename(file);

            let englishName = await processFileName(fileName);
            englishName = formatEnglish(englishName);
            // console.log(englishName);

            // 重命名文件
            const newFilePath = path.join(folderOut, englishName);
            fs.copyFile(filePath, newFilePath, (err) => {
                if (err) {
                    console.error(`Error copying file ${fileName}:`, err);
                } else {
                    console.log(`Successfully copied ${fileName} to ${englishName}`);
                }
            });

        } catch (error) {
            console.error('Error translating or renaming file:', error);
        }

    }
});

const processFileName = async (fileName) => {
    // 重命名逻辑....可扩展    
}


/**
 * 常见单词替换,避免文件名过长,后续有需求也可以继续添加
 */
const formatEnglish = (english) => {
    if (english?.includes('background')) {
        english = english.replaceAll('background', 'bg');
    }
    if (english?.includes('button')) {
        english = english.replaceAll('button', 'btn');
    }
    return english;
}

使用

将文件拷贝进切图 文件夹

运行 node index.js

重命名之后的代码 在 输出 文件夹中

仓库

参考代码 github:github.com/xxhe1024/fi…

gitte:gitee.com/xxhe1024/fi…