( absolutePathToFile: string, data: string, flag?: string, )
| 572 | * @throws FileSystemAccessError for any other error. |
| 573 | */ |
| 574 | export async function writeUtf8File( |
| 575 | absolutePathToFile: string, |
| 576 | data: string, |
| 577 | flag?: string, |
| 578 | ): Promise<void> { |
| 579 | const dirPath = path.dirname(absolutePathToFile); |
| 580 | const dirExists = await exists(dirPath); |
| 581 | if (!dirExists) { |
| 582 | await mkdir(dirPath); |
| 583 | } |
| 584 | |
| 585 | try { |
| 586 | await fsPromises.writeFile(absolutePathToFile, data, { |
| 587 | encoding: "utf8", |
| 588 | flag, |
| 589 | }); |
| 590 | } catch (e) { |
| 591 | ensureNodeErrnoExceptionError(e); |
| 592 | // if the directory was created, we should remove it |
| 593 | if (dirExists === false) { |
| 594 | try { |
| 595 | await remove(dirPath); |
| 596 | // we don't want to override the original error |
| 597 | } catch (_error) {} |
| 598 | } |
| 599 | |
| 600 | if (e.code === "ENOENT") { |
| 601 | throw new FileNotFoundError(absolutePathToFile, e); |
| 602 | } |
| 603 | |
| 604 | // flag "x" has been used and the file already exists |
| 605 | if (e.code === "EEXIST") { |
| 606 | throw new FileAlreadyExistsError(absolutePathToFile, e); |
| 607 | } |
| 608 | |
| 609 | throw new FileSystemAccessError(e.message, e); |
| 610 | } |
| 611 | } |
| 612 | |
| 613 | /** |
| 614 | * Reads a file and returns its content as a Uint8Array. |
no test coverage detected