123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104 |
- import { dirExists } from "#utils";
- import { files_insert } from "#db";
- import crypto from "crypto";
- import fs from "node:fs";
- export async function saveImgs( epub ) {
- // const res = await Promise.allSettled(imgs.map(elm => {
- // }))
- let imgs = epub.listImage();
- console.log(imgs[0]);
- console.log(1121, imgs.length);
- await epub.getImageAsync(imgs[2].id).then(async function ( [data,mimeType] ) {
- console.log(`\ngetImage: cover\n`);
- console.log(data);
- const img_md5 = await calculateMD5FromBuffer(data);
- console.log(img_md5);
- console.log(mimeType);
- console.log(1616,formatSize(data.length));
- const params = {
- file_id: img_md5,
- md5: img_md5,
- mimetype: mimeType,
- size: data.length,
- name: imgs[0].id,
- path: imgs[0].href,
- }
- const uploadPath = "./base_files/" + img_md5;
- dirExists("./base_files/");
- // 如果需要将 JSON 保存为文件,可以使用 fs.writeFile()
- fs.writeFile(uploadPath,data,( err ) => {
- if ( err ) {
- console.error("Error writing JSON file:",err);
- } else {
- console.log("JSON data saved to output.json");
- }
- });
- await files_insert(params)
- });
- }
- function calculateMD5( filePath ) {
- const hash = crypto.createHash("md5");
- const stream = fs.createReadStream(filePath);
- stream.on("data",( chunk ) => {
- hash.update(chunk);
- });
- stream.on("end",() => {
- console.log("MD5 hash:",hash.digest("hex"));
- });
- }
- export async function calculateMD5FromStream( fileStream ) {
- return new Promise(( resolve,reject ) => {
- const hash = crypto.createHash("md5");
- // 错误处理
- fileStream.on("error",( err ) => {
- console.error("Error reading file stream:",err);
- reject("生成失败!"); // 使用 reject 传递错误信息
- });
- // 监听 'data' 事件,更新 MD5 哈希
- fileStream.on("data",( chunk ) => {
- hash.update(chunk);
- });
- // 监听 'end' 事件,文件读取完毕后输出 MD5 值
- fileStream.on("end",() => {
- const md5 = hash.digest("hex");
- console.log("MD5 Hash:",md5);
- resolve(md5); // 正常计算完 MD5 后 resolve
- });
- });
- }
- export function calculateMD5FromBuffer( buffer ) {
- return new Promise(( resolve,reject ) => {
- try {
- // 使用 crypto 计算 MD5
- const hash = crypto.createHash("md5");
- hash.update(buffer); // 直接更新 hash
- const md5 = hash.digest("hex"); // 获取最终的 MD5 值
- console.log("MD5 Hash:",md5);
- resolve(md5); // 返回 MD5
- } catch ( err ) {
- console.error("Error calculating MD5:",err);
- reject("生成失败!");
- }
- });
- }
- const formatSize = ( bytes ) => {
- if ( bytes < 1024 ) return `${ bytes } 字节`;
- else if ( bytes < 1024 * 1024 ) return `${ ( bytes / 1024 ).toFixed(2) } KB`;
- else if ( bytes < 1024 * 1024 * 1024 )
- return `${ ( bytes / ( 1024 * 1024 ) ).toFixed(2) } MB`;
- else return `${ ( bytes / ( 1024 * 1024 * 1024 ) ).toFixed(2) } GB`;
- };
|