@ happyvertical/ files (欢快的垂直/文件)
Have SDK的统一文件系统接口. 在整个本地文件系统提供一致的 API (Node.js) fs/promises)和Google Drive,拥有有费率限制的取取公用设施和遗留的相容性帮助.
安装
pnpm add @happyvertical/files
被放入npm.happyvertical.com并被镜像到公共npm,这可以被放入后退(参见root README的安装注释). 取决于
@happyvertical/utils。 。 。 .
使用量
工厂函数
import { getFilesystem } from '@happyvertical/files';
// Local filesystem (default)
const fs = await getFilesystem({ type: 'local', basePath: '/app/data' });
await fs.write('output/result.txt', 'Hello, world!');
const content = await fs.read('config.json');
const exists = await fs.exists('config.json');
// List files with filtering
const files = await fs.list('.', { filter: /\.json$/, detailed: true });
for (const file of files) {
console.log(`${file.name}: ${file.size} bytes, ${file.mimeType}`);
}
谷歌驱动器
import { getFilesystem } from '@happyvertical/files';
const fs = await getFilesystem({
type: 'gdrive',
clientId: 'xxx',
clientSecret: 'yyy',
refreshToken: 'zzz',
});
await fs.write('documents/readme.txt', 'Hello from Drive');
const content = await fs.read('documents/readme.txt');
支持OAuth2,服务账户密钥,以及短寿命的访问符. Google Docs 本地格式会自动导出(Docs → text, Sheets → CSV等)用于遗留路径 API.
驱动目录的发现和被钉入的获取
GoogleDriveProvider 还曝光基于ID的 Drive 运行目录
适应器. listMetadataPage() 执行只使用元数据、一字串的页码;
坚持返回 nextPageToken 并排入文件夹 ID 以获取
相续转相. 它从来不要求媒体或出口内容.
import { GoogleDriveProvider } from '@happyvertical/files';
const drive = new GoogleDriveProvider({
type: 'gdrive',
accessToken: process.env.DRIVE_READ_TOKEN,
folderId: 'configured-source-root',
// Optional additional source roots and shared-drive support:
allowedFolderIds: ['configured-source-root'],
sharedDriveId: 'shared-drive-id',
});
const page = await drive.listMetadataPage({ pageToken: checkpoint });
// page.entries include stable id, revisionId, parents, driveId, and shortcut metadata.
const snapshot = await drive.acquireById(page.entries[0].id, {
expectedRevision: page.entries[0].revisionId,
maxBytes: 25 * 1024 * 1024,
// Native Docs/Sheets/Slides require an intentional export format.
exportMimeType: 'application/pdf',
});
acquireById() 验证祖先范围与 allowedFolderIds,验证
快捷键目标独立,带硬字节绑定的流,检查
收购前后驱动修改,并返回一款SHA-256内容散列.
使用 application/pdf 用于需要布局保存打印的本地文件.
它从不将证书存储在退回的元数据中.
文件操作
await fs.copy('source.txt', 'backup/source-copy.txt');
await fs.move('temp.txt', 'archive/temp.txt');
await fs.createDirectory('secure-data', { mode: 0o700 });
await fs.delete('temporary-file.txt');
const stats = await fs.getStats('document.pdf');
console.log(`${stats.size} bytes, modified ${stats.mtime}`);
获取公用事业
速率限制的 HTTP 获取远程内容下载的帮助 :
import { fetchText, fetchJSON, fetchBuffer, fetchToFile, addRateLimit } from '@happyvertical/files';
// Set per-domain rate limits
addRateLimit('api.github.com', 30, 60000);
const html = await fetchText('https://example.com');
const data = await fetchJSON('https://api.example.com/data');
const buf = await fetchBuffer('https://example.com/image.png');
await fetchToFile('https://example.com/file.zip', './downloads/file.zip');
安全检查
在决定是否接受上传前检查不信任的ZIP元数据.
@happyvertical/files/archive 是一个独立的浏览器安全条目,只使用 Web
APIs,带有Node导入. 从节点根导出相同的 API :
import {
inspectZipManifest,
ZipManifestError,
ZipManifestLimitError,
} from '@happyvertical/files/archive';
try {
const manifest = inspectZipManifest(zipBytes, {
maxEntries: 2_000,
maxEntryUncompressedBytes: 50 * 1024 * 1024,
maxTotalUncompressedBytes: 500 * 1024 * 1024,
});
const files = manifest.entries
.filter((entry) => entry.type === 'file')
.map(({ path, size }) => ({ path, size }));
} catch (error) {
if (error instanceof ZipManifestLimitError) {
console.error(error.limit, error.actual, error.maximum);
} else if (error instanceof ZipManifestError) {
console.error(error.code, error.message);
}
}
inspectZipManifest() 阅读和交叉核对中央-主任和地方主管
仅限元数据。 它不会解压或实现文件机构。 路径是
带回 / 分离器和 ./空块被删除; 包含
普通空间仍然有效。 整个归档被拒绝为父文件
逆向、绝对/驱动合格路径, NTFS 替代数据流路径
包含冒号、 NUL 字节、 Unix 符号链接和特殊文件, Windows reparse
点和保留设备名称、以点或空格结尾的路径段,
大小写不敏感或 Unicode- 正常化路径相撞、 文件/ 后传路径
冲突、重叠的本地输入范围,或
中心目录.
默认限制为一万个条目,每个条目200个米B,宣布2个吉B总量 未压缩大小,和1,024编码路径字节. 条目数包括目录 条目,且总大小包括每个条目。 所有限制都是可配置的 与非负安全整数。 条目限制还限制累积 中央指导工作,同时在敌对评论中混淆最终记录.
政策刻意严格:ZIP64,加密,多盘,畸形,
截断的,模棱两可的终极记录,以及非UTF-8名称的档案被拒绝使用
输入错误。 存储条目还必须声明相同的压缩和
未压缩大小,每个本地头和压缩有效载荷必须使用
不同范围。 这些引用范围必须集体覆盖每个字节
在中央目录之前,将序言、补丁空白和本地
中心目录中省略的条目被拒绝。 签署和未签署
经典数据描述符仅用于存储和压缩条目
payloadStart + centralCompressedSize它们的CRC和尺寸必须与
中央目录,本地字段必须是零或匹配的. 描述字节
参与相同的重叠和完整覆盖检查; 内部签名
有效载荷从未被扫描过。 这些是元数据检查:消费者必须仍然
控制实际通货膨胀,独立核实产出大小和CRC。 条目
名称使用严格的UTF-8解码,无论UTF-8旗是否被设定. 领导
UTF-8 BOMs 被拒绝,因为文件名解码器对BOM是否存在分歧
是已提取路径的一部分; 常见的 macOS ZIP , 并保留有效的 UTF-8 名称
兼容.
PKWARE 替代编码、 Info- ZIP 和 Xceed 路径额外字段被拒绝
因此,提取器不能从中选择不同的路径或字符编码
一个检查。 PKWARE和ASi Unix额外字段同样被否决,因为
它们可以提供链接目标;
自由主义 xl 字段被拒绝,因为它可以覆盖已检查的文件
类型。 Unix 文件类型比特只为 Unix 或 Darwin 源代码中心获得荣誉
头; DOS、 NTFS 或其他创建系统声称的文件类型比特是
拒绝。 这些交替元数据案件以及相矛盾的Unix文件
和目录属性, 使用
UnsupportedZipFeatureError 与 ambiguous-metadata 特性。 这个API是
元数据预飞,而不是提取 API; 消费者,后取
已接受的归档仍必须使用提取目的地和库
等同路径和同义链接保护.
处理错误
import { FileNotFoundError, PermissionError, DirectoryNotEmptyError } from '@happyvertical/files';
try {
await fs.read('missing.txt');
} catch (error) {
if (error instanceof FileNotFoundError) {
console.error('Not found:', error.path);
} else if (error instanceof PermissionError) {
console.error('Permission denied:', error.path);
}
}
绑定的读取和创建- 无覆盖
所有提供者都接受一个字节上限,用于阅读和拒绝上面的内容
FileSizeLimitExceededError。 S3 供应商执行上限时
消耗响应流,包括没有内容长度的响应.
const object = await fs.read('objects/sha256.bin', {
raw: true,
maxBytes: 10 * 1024 * 1024,
});
await fs.write('objects/sha256.bin', object, { overwrite: false });
overwrite: false 是本地供应商的原子创建操作。 第3条
失败 ConditionalWriteUnsupportedError 除非
其选项明确声明 conditionalWriteStrategy: 'if-none-match'。 。 。 .
仅在已解决的终点合同有文件证明时设定该选项
保障PUT的荣誉 If-None-Match: *; 接受无
执行它是不够的。 设置甚至对本地的 AWS S3 都明确
因为AWS SDK环境配置可以使终点重定向. 现有
目的地提升 FileExistsError 绝不是覆写者。 并行 S3
操作提高可重试 ConditionalWriteConflictError (单位:千美元)EAGAIN) (中文(简体) ).
遗留函数
从原 API 中独立函数, 仍然导出后向兼容性 :
import { isFile, isDirectory, ensureDirectoryExists, download, listFiles } from '@happyvertical/files';
const fileStats = isFile('/path/to/file.txt'); // synchronous
const isDir = isDirectory('/path/to/dir'); // synchronous
await ensureDirectoryExists('/path/to/new/dir');
await download('https://example.com/file.pdf', './file.pdf');
const files = await listFiles('/path/to/dir', { match: /\.json$/ });
供应商
| 提供者 | 状态 | 选项 |
|---|---|---|
| 当地 | 已执行 | basePath? |
| 谷歌驱动器 | 已执行 | clientId, (中文(简体) ), clientSecret, (中文(简体) ), refreshToken (或 serviceAccountKey 编号 : accessToken(中文(简体) ) |
| 第3条 | 已执行 | region, (中文(简体) ), bucket, (中文(简体) ), accessKeyId?, (中文(简体) ), secretAccessKey?, (中文(简体) ), endpoint?, (中文(简体) ), conditionalWriteStrategy? |
| 网络数据交换 | 仅类型 | baseUrl, (中文(简体) ), username, (中文(简体) ), password |
API 概览
工厂数字 : getFilesystem(options), (中文(简体) ), registerProvider(type, factory), (中文(简体) ), getAvailableProviders(), (中文(简体) ), isProviderAvailable(type), (中文(简体) ), getProviderInfo(type)
提供者类别数字 : LocalFilesystemProvider, (中文(简体) ), GoogleDriveProvider, (中文(简体) ), S3FilesystemProvider
接口方法数字 : exists, (中文(简体) ), read, (中文(简体) ), write, (中文(简体) ), delete, (中文(简体) ), copy, (中文(简体) ), move, (中文(简体) ), createDirectory, (中文(简体) ), list, (中文(简体) ), getStats, (中文(简体) ), getMimeType, (中文(简体) ), upload, (中文(简体) ), download, (中文(简体) ), downloadWithCache, (中文(简体) ), cache.get/set/clear, (中文(简体) ), getCapabilities
获取数字 : fetchText, (中文(简体) ), fetchJSON, (中文(简体) ), fetchBuffer, (中文(简体) ), fetchToFile, (中文(简体) ), addRateLimit, (中文(简体) ), getRateLimit
档案检查数字 : inspectZipManifest, (中文(简体) ), DEFAULT_ZIP_MANIFEST_LIMITS, (中文(简体) ), ZipManifestError, (中文(简体) ), InvalidZipArchiveError, (中文(简体) ), UnsafeZipEntryError, (中文(简体) ), ZipManifestLimitError, (中文(简体) ), UnsupportedZipFeatureError
错误数字 : FilesystemError, (中文(简体) ), FileNotFoundError, (中文(简体) ), PermissionError, (中文(简体) ), DirectoryNotEmptyError, (中文(简体) ), InvalidPathError
遗产数字 : isFile, (中文(简体) ), isDirectory, (中文(简体) ), ensureDirectoryExists, (中文(简体) ), download, (中文(简体) ), upload, (中文(简体) ), downloadFileWithCache, (中文(简体) ), listFiles, (中文(简体) ), getCached, (中文(简体) ), setCached, (中文(简体) ), getMimeType
依赖关系
@happyvertical/utils——临时目录管理googleapis编号 :google-auth-library——谷歌驱动器提供商