90 lines
2.6 KiB
JavaScript
90 lines
2.6 KiB
JavaScript
const { PrismaClient } = require('@prisma/client')
|
|
const fs = require('fs')
|
|
const path = require('path')
|
|
|
|
const prisma = new PrismaClient()
|
|
|
|
async function updateFileSizes() {
|
|
console.log('开始扫描文件并更新数据库...\n')
|
|
|
|
try {
|
|
// 获取所有素材记录
|
|
const materials = await prisma.material.findMany({
|
|
select: {
|
|
id: true,
|
|
zipFilePath: true,
|
|
zipFileName: true,
|
|
zipFileSize: true,
|
|
}
|
|
})
|
|
|
|
console.log(`找到 ${materials.length} 条素材记录\n`)
|
|
|
|
let updatedCount = 0
|
|
let notFoundCount = 0
|
|
let unchangedCount = 0
|
|
|
|
for (const material of materials) {
|
|
try {
|
|
// 构建文件完整路径
|
|
const filePath = path.join(process.cwd(), material.zipFilePath)
|
|
|
|
// 检查文件是否存在
|
|
if (!fs.existsSync(filePath)) {
|
|
console.log(`❌ 文件不存在: ${material.zipFileName}`)
|
|
console.log(` 路径: ${filePath}\n`)
|
|
notFoundCount++
|
|
continue
|
|
}
|
|
|
|
// 获取文件大小
|
|
const stats = fs.statSync(filePath)
|
|
const actualSize = BigInt(stats.size)
|
|
const currentSize = BigInt(material.zipFileSize)
|
|
|
|
// 如果大小不同,更新数据库
|
|
if (actualSize !== currentSize) {
|
|
await prisma.material.update({
|
|
where: { id: material.id },
|
|
data: { zipFileSize: actualSize }
|
|
})
|
|
|
|
console.log(`✅ 更新: ${material.zipFileName}`)
|
|
console.log(` 原大小: ${formatSize(currentSize)}`)
|
|
console.log(` 新大小: ${formatSize(actualSize)}\n`)
|
|
updatedCount++
|
|
} else {
|
|
unchangedCount++
|
|
}
|
|
} catch (error) {
|
|
console.error(`错误处理文件 ${material.zipFileName}:`, error.message)
|
|
}
|
|
}
|
|
|
|
console.log('\n========================================')
|
|
console.log('扫描完成!')
|
|
console.log(`总计: ${materials.length} 条记录`)
|
|
console.log(`✅ 已更新: ${updatedCount} 条`)
|
|
console.log(`➡️ 未变化: ${unchangedCount} 条`)
|
|
console.log(`❌ 文件不存在: ${notFoundCount} 条`)
|
|
console.log('========================================\n')
|
|
|
|
} catch (error) {
|
|
console.error('执行失败:', error)
|
|
} finally {
|
|
await prisma.$disconnect()
|
|
}
|
|
}
|
|
|
|
function formatSize(bytes) {
|
|
const size = Number(bytes)
|
|
if (size === 0) return '0 B'
|
|
const units = ['B', 'KB', 'MB', 'GB', 'TB']
|
|
const i = Math.floor(Math.log(size) / Math.log(1024))
|
|
return `${(size / Math.pow(1024, i)).toFixed(2)} ${units[i]}`
|
|
}
|
|
|
|
// 执行脚本
|
|
updateFileSizes()
|
|
|