fenghuo/apps/backend/src/utils/file.ts

68 lines
2.1 KiB
TypeScript

import { createHash } from 'crypto';
import { createReadStream } from 'fs';
import path from 'path';
import * as dotenv from 'dotenv';
import dayjs from 'dayjs';
dotenv.config();
export function getFilenameWithoutExt(filename: string | null | undefined) {
return filename ? filename.replace(/\.[^/.]+$/, '') : filename || dayjs().format('YYYYMMDDHHmmss');
}
/**
* 计算文件的 SHA-256 哈希值
* @param filePath 文件路径
* @returns Promise<string> 返回文件的哈希值(十六进制字符串)
*/
export async function calculateFileHash(filePath: string): Promise<string> {
return new Promise((resolve, reject) => {
// 创建一个 SHA-256 哈希对象
const hash = createHash('sha256');
// 创建文件读取流
const readStream = createReadStream(filePath);
// 处理读取错误
readStream.on('error', (error) => {
reject(new Error(`Failed to read file: ${error.message}`));
});
// 处理哈希计算错误
hash.on('error', (error) => {
reject(new Error(`Failed to calculate hash: ${error.message}`));
});
// 流式处理文件内容
readStream
.pipe(hash)
.on('finish', () => {
// 获取最终的哈希值(十六进制格式)
const fileHash = hash.digest('hex');
resolve(fileHash);
})
.on('error', (error) => {
reject(new Error(`Hash calculation failed: ${error.message}`));
});
});
}
/**
* 计算 Buffer 的 SHA-256 哈希值
* @param buffer 要计算哈希的 Buffer
* @returns string 返回 Buffer 的哈希值(十六进制字符串)
*/
export function calculateBufferHash(buffer: Buffer): string {
const hash = createHash('sha256');
hash.update(buffer);
return hash.digest('hex');
}
/**
* 计算字符串的 SHA-256 哈希值
* @param content 要计算哈希的字符串
* @returns string 返回字符串的哈希值(十六进制字符串)
*/
export function calculateStringHash(content: string): string {
const hash = createHash('sha256');
hash.update(content);
return hash.digest('hex');
}
export const getUploadFilePath = (fileId: string): string => {
const uploadDirectory = process.env.UPLOAD_DIR || '';
return path.join(uploadDirectory, fileId);
};