| 83 | type WriteFileOptions = BufferEncoding | { encoding?: BufferEncoding; recursive?: boolean }; |
| 84 | |
| 85 | export class FileSystemApi { |
| 86 | constructor(private readonly channel: MessageSender) {} |
| 87 | |
| 88 | /** |
| 89 | * Initialize the File System worker with the files. |
| 90 | */ |
| 91 | public async init(files: FilesMap): Promise<void> { |
| 92 | // Await the sent event to know when the worker |
| 93 | // is done writing the files. |
| 94 | await this.channel.send('fs/init', { files }); |
| 95 | } |
| 96 | |
| 97 | /** |
| 98 | * Read a file at the given path. |
| 99 | */ |
| 100 | public async readFile(path: string, encoding?: undefined): Promise<Uint8Array>; |
| 101 | public async readFile(path: string, encoding: 'buffer'): Promise<Uint8Array>; |
| 102 | public async readFile(path: string, encoding: BufferEncoding): Promise<string>; |
| 103 | |
| 104 | public async readFile(path: string, encoding?: FSEncoding): Promise<FileContent> { |
| 105 | const response = await this.channel.send('fs/readFile', { path, encoding }).catch((error) => { |
| 106 | throw new Error(format('Failed to read file at path "%s"', path), { cause: error }); |
| 107 | }); |
| 108 | if (!response) { |
| 109 | throw new Error('File not found'); |
| 110 | } |
| 111 | return response.data; |
| 112 | } |
| 113 | |
| 114 | /** |
| 115 | * Write a file at the given path. |
| 116 | * Replaces the file content if the file already exists. |
| 117 | */ |
| 118 | public async writeFile(path: string, content: FileContent): Promise<void>; |
| 119 | public async writeFile(path: string, content: FileContent, options: WriteFileOptions): Promise<void>; |
| 120 | |
| 121 | public async writeFile(path: string, content: FileContent, options?: WriteFileOptions): Promise<void> { |
| 122 | let encoding = undefined; |
| 123 | let recursive = false; |
| 124 | |
| 125 | if (typeof options === 'object') { |
| 126 | encoding = options.encoding; |
| 127 | recursive = !!options.recursive; |
| 128 | } else if (typeof options === 'string') { |
| 129 | encoding = options; |
| 130 | } |
| 131 | |
| 132 | await this.channel.send('fs/writeFile', { path, content, encoding, recursive }).catch((error) => { |
| 133 | throw new Error(format('Failed to write file at path "%s"', path), { cause: error }); |
| 134 | }); |
| 135 | } |
| 136 | |
| 137 | public async readdir(path: string): Promise<string[]> { |
| 138 | const response = await this.channel.send('fs/readdir', { path }).catch((error) => { |
| 139 | throw new Error(format('Failed to read directory at path "%s"', path), { cause: error }); |
| 140 | }); |
| 141 | if (!response) { |
| 142 | throw new Error('Directory not found'); |
nothing calls this directly
no outgoing calls
no test coverage detected