标签:pre ext 时间戳 crypto res dir lse 备份 ash
这类似一个备份功能, 只会保存更新, 比如后端的接口文档经常变, 然后可以用此工具来保存更新记录.
new Promise(async () => {
setInterval(() => {
// const fileUrl = `http://172.16.203.82:8203/v3/api-docs`
const fileUrl = `http://127.0.0.1:9070/file`
backUrl(fileUrl)
}, 1000)
})
async function backUrl(fileUrl) {
const { data: fileData, ext: fileExt } = await getFile(fileUrl)
const {
pathname,
fileName,
} = getFilePath(fileUrl)
console.log(`getFilePathRes`, `${pathname}/${fileName}`)
const fs = require(‘fs‘)
const dir = `${__dirname}/${pathname}`
fs.mkdirSync(dir, { recursive: true })
console.log(`dirdir`, dir)
const maxTime = fs.readdirSync(dir).filter(item => { // 获取所有备份的文件
return item.match(/_\d{13}_back/)
}).map(item => { // 获取所有时间戳
return Number(item.match(/(\d{13})/)[1])
}).sort().reverse()[0] // 获取最大的那个时间戳
console.log(`maxTime`, maxTime)
if (maxTime) {
const oldMd5 = getFileMd5(fs.readFileSync(`${dir}/${fileName}_${maxTime}_back.${fileExt}`))
const tempFile = `${dir}/temp`
saveFile(tempFile, fileData)
const newMd5 = getFileMd5(fs.readFileSync(tempFile))
fs.unlinkSync(tempFile)
console.log({ oldMd5, newMd5 })
if (oldMd5 !== newMd5) {
saveFile(`${dir}/${fileName}_${Date.now()}_back.${fileExt}`, fileData)
}
} else {
saveFile(`${dir}/${fileName}_${Date.now()}_back.${fileExt}`, fileData)
}
}
function getFileMd5(pathOrBuffer, type) { // 获取文件 md5
const fs = require(`fs`)
const buffer = type === `path` ? fs.readFileSync(pathOrBuffer) : pathOrBuffer
const crypto = require(‘crypto‘);
const md5 = crypto.createHash(‘md5‘).update(buffer).digest(‘hex‘)
return md5
}
// 获取文件的存储路径
function getFilePath(url) {
const filenamify = require(‘filenamify‘)
const {
pathname,
origin,
} = new URL(url)
const fileName = filenamify(
url.replace(origin + pathname, ``),
{ maxLength: 255, replacement: ‘_‘ }
)
return {
pathname,
fileName,
}
}
// 请求文件
function getFile(url) {
return new Promise((resolve, reject) => {
const http = require(`http`)
http.get(url, res => {
const { statusCode } = res
if (statusCode !== 200) {
reject(statusCode)
}
let data = ‘‘
res.setEncoding(‘binary‘)
res.on(‘data‘, (chunk) => {
data += chunk
});
res.on(‘end‘, () => {
const mime = require(‘mime‘)
const ext = mime.getExtension(res.headers[`content-type`]) || ``
resolve({
data,
ext,
})
})
})
})
}
// 保存文件,目录是 url 路径,名称是请求的返回结果时间 【yyyy-mm-dd hh-MM-ss.后缀名】
function saveFile(filePath, bin) {
const fs = require(‘fs‘)
fs.writeFileSync(filePath, bin, { encoding: ‘binary‘ })
}
标签:pre ext 时间戳 crypto res dir lse 备份 ash
原文地址:https://www.cnblogs.com/daysme/p/14719543.html