欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

JavaScript實(shí)現(xiàn)批量重命名文件

 更新時(shí)間:2024年12月12日 10:42:02   作者:Face  
這篇文章主要為大家詳細(xì)介紹了如何利用JavaScript實(shí)現(xiàn)批量重命名文件,文中的示例代碼講解詳細(xì),有需要的小伙伴可以跟隨小編一起學(xué)習(xí)一下

批量重命名圖片

改下載的圖片中的名稱時(shí)候,感覺一個(gè)個(gè)修改太麻煩了,就像寫個(gè)腳本執(zhí)行一下,順便多熟悉一下node的fs模塊

一次性對某一文件夾下多個(gè)圖片文件進(jìn)行名稱的修改與調(diào)整,不用逐一手動(dòng)重命名圖片,快速更新文件名,執(zhí)行腳本自動(dòng)修改圖片名

自動(dòng)“9a9f0a7f89a7.jpg”,之類的圖片名為002.jpg

我這里將設(shè)置文件重命名為從0 ~ 999,可以根據(jù)要命名的圖片數(shù)量自定義設(shè)置。

reName.js代碼如下:

const fs = require("fs");
const path = require("path");
// 要修改的文件路徑
const folderPath = "./testPicture";
const imgType = ["jpg", "png", "jpeg", "gif", "bmp", "tiff", "ico", "webp"];

let count = 0;
function pad(num, size) {
	let s = num + "";
	while (s.length < size) s = "0" + s;
	return s;
}

fs.readdir(folderPath, (err, files) => {
	try {
		if (err) {
			console.error("讀取文件出錯(cuò)", err);
			return;
		}
		files.forEach((file) => {
			// 如果用 path.extname() 獲取擴(kuò)展名,注意名稱為空的額外處理
			const ext = file.split(".").at(-1).toLowerCase();		
			if (imgType.includes(ext)) {
				const oldFilePath = path.join(folderPath, file);
				const newFileName = pad(count, 3) + "." + ext;
				const newFilePath = path.join(folderPath, newFileName);
				fs.rename(oldFilePath, newFilePath, (err) => {		
					if (err) console.error("重命名文件出錯(cuò)", err);
				});
				count++;
			}
		});
		console.log(`重命名完成,共重命名 ${count} 個(gè)文件`);
	} catch (error) {
		throw new Error(error);
	}
});

如果要修改重命名其他文件,修改imgType中的文件類型執(zhí)行腳本即可

  • 執(zhí)行腳本直接使用 node 運(yùn)行即可node reName.js
  • 運(yùn)行之前先備份?。。?/strong>

方法補(bǔ)充

除了上文的方法,小編還為大家整理了一些其他JavaScript重命名文件的方法,有需要的可以了解下

方法一:

'use strict'

let fs = require('fs');
let args = process.argv;
let dist = 'dist';
let src = 'src';
let index = 0;
let ignore = '';

// 目標(biāo)路徑
dist = args[2];
// 名字前綴
src = args[3];
// 遞增后綴
index = args[4] || 1;
// ? 忽略的文件
ignore = args[5] || "";

let files = fs.readdirSync(dist);
let sortValue = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
files.sort(function (a, b) {
    let index = -1;
    for (let i = sortValue.length - 1; i >= 0; i--) {
        index = a.indexOf(sortValue[i]);
        if (index != -1) {
            // console.log("a: ", a, " i: ", i, " index: ", index);
            break;
        }
    }

    if (index == -1) {
        return 0;
    }
    else {
        let aid = parseInt(a.substring(index));
        let bid = parseInt(b.substring(index));
        if (aid == NaN || bid == NaN) {
            return 0;
        }
        else {
            return aid - bid;
        }
    }
});

for (let i = 0; i < files.length; i++) {
    if (ignore !== "" && files[i].indexOf(ignore) === -1) {
        continue;
    }
    let stat = fs.statSync(dist + "\\" + files[i]);
    let runRename = function (stat) {
        if (stat.isFile()) {
            let prefix = dist + "\\";
            let suffix = files[i].substring(files[i].indexOf("."));
            let oldName = prefix + files[i];
            let newName = prefix + src + index + suffix;
            fs.renameSync(oldName, newName);
            index++;
        }
    };
    runRename(stat);
}

方法二:js 批量修改文件名后綴

在需要修改的文件夾除創(chuàng)建一個(gè)js文件 ,通過 node .\****.js 運(yùn)行或在創(chuàng)建一個(gè).bat文件:node .****.js pause 后雙擊

記得修改dirName

// 引入 fs 文件系統(tǒng)模塊
let fs = require('fs')

const dirName = 'mus' // 讀取目標(biāo)文件夾名稱
const reg = /(?<=[.])[a-z]+/ // 文件后綴 匹配規(guī)則

// 讀文件夾,獲取文件名列表
let fileList = fs.readdirSync(dirName)

// 過濾出想要的文件類型
let resultList = fileList.reduce((pev, cur) => {
  // 獲取后綴
  const curPicType = cur.match(reg)[0]
  if (['mgg', 'flac', 'ogg', 'lrc'].includes(curPicType)) {
    pev.push(cur)
  }
  return pev
}, [])
console.log('文件列表', resultList)

// 循環(huán)當(dāng)前文件名列表,根據(jù)需要重寫名字
for (let i = 0; i < resultList.length; i++) {
  // 文件完整名稱
  const curFileName = resultList[i]
  // 后綴名
  const fileFormat = curFileName.match(reg)[0]
  // 去掉后綴的文件名
  const fileCode = curFileName.split('.')[0]


  // oldPath 原地址
  const oldPath = `./${dirName}/${curFileName}`
  // newPath 目標(biāo)地址
  let newPath = ''

  // 修改方式
  // 如果想根據(jù)不同條件,將文件分別放到不同的文件夾,按需更改 newPath 即可
  if (fileFormat == 'ogg' || fileFormat == 'mgg') {
    newPath = `./${dirName}/${fileCode}.mp3`
  } else {
    newPath = oldPath
  }

  // 確認(rèn)修改
  fs.rename(oldPath, newPath, (err) => {
    if (err) throw err;
    console.log(`修改成功 -- ${newPath}`);
  })
}

到此這篇關(guān)于JavaScript實(shí)現(xiàn)批量重命名文件的文章就介紹到這了,更多相關(guān)JavaScript重命名文件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論