// 使用说明
// 首先在官网下载node http://nodejs.cn/download/ 就可以在命令行使用node命令了
// 然后把这个文件放在在你需要去重文件的目录下 打开命令行到文件所在目录 输入 node fileDeDuplication 即可
const fs = require("fs")
const crypto = require("crypto")
const readline = require("readline")
const path = require("path")
// 这里需要遍历一下文件获取列表
const md5PathMap = {}
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
})
const supportSuffixs = [".jpg", ".png", ".jpeg"]
let suffix = ""
const paths = []
function deleteFile(path) {
fs.unlinkSync(path)
console.log(`${path} 已被删除`)
}
//文件遍历
function fileDisplay(filePath, suf) {
//根据文件路径读取文件,返回文件列表
const files = fs.readdirSync(filePath)
//遍历读取到的文件列表
files.forEach(function (filename) {
//获取当前文件的绝对路径
var filedir = path.join(filePath, filename)
//根据文件路径获取文件信息,返回一个fs.Stats对象
const stats = fs.statSync(filedir)
var isFile = stats.isFile() //是文件
var isDir = stats.isDirectory() //是文件夹
if (isFile && filename.indexOf(suf) >= 0) {
paths.push(filename)
}
if (isDir) {
fileDisplay(filedir) //递归,如果是文件夹,就继续遍历该文件夹下面的文件
}
})
}
async function dealSingleFile(path) {
return new Promise((res) => {
const start = new Date().getTime()
const md5sum = crypto.createHash("md5")
const stream = fs.createReadStream(path)
stream.on("data", function (chunk) {
md5sum.update(chunk)
})
stream.on("end", function () {
str = md5sum.digest("hex").toUpperCase()
console.log(
"文件: " +
path +
", MD5签名为:" +
str +
". 耗时:" +
(new Date().getTime() - start) / 1000.0 +
"秒"
)
if (md5PathMap[str]) {
console.log("\n出现重复的文件!")
console.log(
`文件: ${md5PathMap[str].join(
", \n文件: "
)}\n与\n当前文件: ${path} 重复`
)
rl.question(
"?请输入要删除的文件路径,如不需要删除输入任意值即可,\n输入: ",
(answer) => {
answer = answer.trim()
md5PathMap[str].push(path)
try {
deleteFile(answer)
md5PathMap[str].splice(md5PathMap[str].indexOf(answer), 1)
} catch (e) {
console.log("删除失败,将保留相同文件")
}
console.log("\n")
res()
}
)
} else {
md5PathMap[str] = [path]
res()
}
})
})
}
;(async () => {
await new Promise((res) => {
rl.question(
"此脚本将会对当前目录下所有文件进行MD5校验, 可以自由选择是否删除重复文件\n?请输入要删除文件的后缀(当前支持 .jpg .png .jpeg 类型): ",
(answer) => {
suffix = answer
if (supportSuffixs.indexOf(answer) < 0) {
console.log("当前脚本不支持此文件类型!程序退出")
rl.close()
return
}
console.log(`将对当前目录下所有${suffix}进行MD5校验, 请稍后...\n`)
setTimeout(() => {
res()
}, 3000)
}
)
})
fileDisplay("./", suffix)
for (let i = 0; i < paths.length; i++) {
await dealSingleFile(paths[i])
}
console.log("\n去重完成!")
rl.close()
})()
文件去重脚本
于 2021-12-29 20:24:30 首次发布