@ chunkd/ fs (中文(简体) )
文件系统抽象层
方便本地文件系统或远程ASync应用程序与文件系统如接口工作
使用量
基础
读取文本文件
import { fsa } from '@chunkd/fs';
const bytes = await fsa.read(fsa.toUrl('../foo.txt'));
列出文件夹
for await (const url of fsa.list(fsa.toUrl('/'))) {
const bytes = await fsa.read(url);
}
多文件系统
注册多个文件系统
import { fsa, FsMemory } from '@chunkd/fs';
fsa.register('memory://', new FsMemory());
await fsa.write(fsa.toUrl('memory://foo.txt'), 'Hello World');
// Stream the file from memory into the local file system
await fsa.write(fsa.toUrl('/foo.txt'), fsa.readStream(fsa.toUrl(()'memory://foo.txt')));
远程文件系统
远程文件系统也可以使用
import { fsa, FsHttp } from '@chunkd/fs';
import { FsAwsS3 } from '@chunkd/fs-aws';
fsa.register('https://', new FsHttp());
fsa.register('s3://', new FsAwsS3());
// Stream a file from https://example.com into AWS S3
await fsa.write(fsa.toUrl('s3://example/foo.txt'), fsa.readStream(fsa.toUrl('https://example.com/foo.txt')));
多个 S3 证书
多个 s3 客户端可以用不同的证书注册,然后用于在 AWS 账户或角色之间流出文件
import { fsa } from '@chunkd/fs';
import { FsAwsS3 } from '@chunkd/fs-aws';
fsa.register('s3://bucket-a/', new FsAwsS3(new S3Client({ credentials: bucketA })));
fsa.register('s3://bucket-b/', new FsAwsS3(new S3Client({ credentials: bucketB })));
fsa.write(fsa.toUrl('s3://bucket-a/foo.txt'), fsa.readStream(fsa.toUrl('s3://bucket-b/foo.txt')));
错误
所有文件系统错误都应该被包入一个 FsError
try {
await fsa.read('s3://foo/bar.txt')
} catch(e) {
if(FsError.is(e)) {
e.status // Http Status code eg 403
e.cause // original error
e.action // `read`
e.url // `s3://foo/bar.txt`
}
}
# Interface
All file systems implement then following interface interface
```typescript
export interface FileSystem {
/** Read a file into a buffer */
read(location: URL): Promise<Buffer>;
/** Create a read stream */
readStream(location: URL): Readable;
/** Write a file from either a buffer or stream */
write(location: URL, buffer: Buffer | Readable | string, opts?: Partial<WriteOptions>): Promise<void>;
/** list all files in path */
list(location: URL, opt?: ListOptions): AsyncGenerator<URL>;
/** list all files with file info in path */
details(location: URL, opt?: ListOptions): AsyncGenerator<FileInfo>;
/** Get information about the path */
head(location: URL): Promise<FileInfo | null>;
/** Create a chunk source to read chunks out of */
source(location: URL): Source;
/** Delete a file from the location */
delete(location: URL): Promise<void>;
}