File size: 6,378 Bytes
3246b69 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 | /**
* 本地 R2 存储适配器
* 使用本地文件系统模拟 Cloudflare R2 的 API 接口
*/
import { readFileSync, writeFileSync, unlinkSync, existsSync, mkdirSync, readdirSync, statSync, rmSync } from 'fs';
import { dirname, join } from 'path';
import { createReadStream } from 'fs';
import { Readable } from 'stream';
import { randomUUID } from 'crypto';
export class LocalR2Storage {
constructor(basePath) {
this.basePath = basePath;
mkdirSync(basePath, { recursive: true });
}
_filePath(key) {
return join(this.basePath, key);
}
/**
* 获取文件(模拟 R2 的 get 方法)
* 支持 Range 请求
*/
async get(key, options) {
const filePath = this._filePath(key);
if (!existsSync(filePath)) return null;
const stats = statSync(filePath);
const size = stats.size;
let body;
let range;
if (options && options.range) {
const offset = options.range.offset || 0;
const length = options.range.length || (size - offset);
const end = offset + length - 1;
const nodeStream = createReadStream(filePath, { start: offset, end: end });
body = Readable.toWeb(nodeStream);
range = { offset, length };
} else {
const nodeStream = createReadStream(filePath);
body = Readable.toWeb(nodeStream);
}
return {
body,
size,
range,
httpMetadata: {},
writeHttpMetadata(headers) {
// 本地存储不设置额外的 HTTP 元数据
}
};
}
/**
* 存储文件(模拟 R2 的 put 方法)
* 支持多种输入类型
*/
async put(key, value) {
const filePath = this._filePath(key);
mkdirSync(dirname(filePath), { recursive: true });
let buffer;
if (value instanceof Blob || (typeof File !== 'undefined' && value instanceof File)) {
buffer = Buffer.from(await value.arrayBuffer());
} else if (value instanceof ArrayBuffer) {
buffer = Buffer.from(value);
} else if (value instanceof Uint8Array || Buffer.isBuffer(value)) {
buffer = Buffer.from(value);
} else if (value instanceof ReadableStream) {
const reader = value.getReader();
const chunks = [];
while (true) {
const { done, value: chunk } = await reader.read();
if (done) break;
chunks.push(chunk);
}
buffer = Buffer.concat(chunks);
} else if (typeof value === 'string') {
buffer = Buffer.from(value, 'utf-8');
} else {
buffer = Buffer.from(String(value), 'utf-8');
}
writeFileSync(filePath, buffer);
}
/**
* 删除文件(模拟 R2 的 delete 方法)
*/
async delete(key) {
const filePath = this._filePath(key);
if (existsSync(filePath)) {
unlinkSync(filePath);
}
}
/**
* 创建分块上传(模拟 R2 的 createMultipartUpload 方法)
*/
async createMultipartUpload(key) {
const uploadId = randomUUID();
const uploadDir = join(this.basePath, '_multipart', uploadId);
mkdirSync(uploadDir, { recursive: true });
// 保存 key 映射
writeFileSync(join(uploadDir, '_key'), key);
return {
uploadId,
key,
...this._createMultipartMethods(key, uploadId)
};
}
/**
* 恢复分块上传(模拟 R2 的 resumeMultipartUpload 方法)
*/
resumeMultipartUpload(key, uploadId) {
return {
uploadId,
key,
...this._createMultipartMethods(key, uploadId)
};
}
_createMultipartMethods(key, uploadId) {
const self = this;
const uploadDir = join(this.basePath, '_multipart', uploadId);
return {
async uploadPart(partNumber, data) {
mkdirSync(uploadDir, { recursive: true });
const partPath = join(uploadDir, `part_${String(partNumber).padStart(6, '0')}`);
let buffer;
if (data instanceof ArrayBuffer) {
buffer = Buffer.from(data);
} else if (data instanceof Uint8Array || Buffer.isBuffer(data)) {
buffer = Buffer.from(data);
} else if (data instanceof Blob) {
buffer = Buffer.from(await data.arrayBuffer());
} else if (data instanceof ReadableStream) {
const reader = data.getReader();
const chunks = [];
while (true) {
const { done, value: chunk } = await reader.read();
if (done) break;
chunks.push(chunk);
}
buffer = Buffer.concat(chunks);
} else {
buffer = Buffer.from(data);
}
writeFileSync(partPath, buffer);
return { etag: `etag_${partNumber}`, partNumber };
},
async complete(parts) {
// 按 partNumber 排序合并所有分块
const sortedParts = parts.sort((a, b) => a.partNumber - b.partNumber);
const chunks = [];
for (const part of sortedParts) {
const partPath = join(uploadDir, `part_${String(part.partNumber).padStart(6, '0')}`);
if (existsSync(partPath)) {
chunks.push(readFileSync(partPath));
}
}
const merged = Buffer.concat(chunks);
await self.put(key, merged);
// 清理分块目录
self._cleanupDir(uploadDir);
},
async abort() {
// 清理分块目录
self._cleanupDir(uploadDir);
}
};
}
_cleanupDir(dir) {
if (existsSync(dir)) {
try {
rmSync(dir, { recursive: true, force: true });
} catch (e) {
console.error('Cleanup error:', e.message);
}
}
}
}
|