summaryrefslogtreecommitdiff
path: root/std/fs/ensure_file.ts
diff options
context:
space:
mode:
authorAxetroy <axetroy.dev@gmail.com>2019-12-18 22:45:19 +0800
committerRy Dahl <ry@tinyclouds.org>2019-12-18 09:45:19 -0500
commitef30d376db94bda24ed31947a1cc264b827705dc (patch)
treeaba58a06c797efd513a1a83ba056487e18674d6f /std/fs/ensure_file.ts
parent1c09cc63c8b9c33842ee302c93aebc6593be8b15 (diff)
fix permission errors are swallowed by fs.copy() (#3504)
Diffstat (limited to 'std/fs/ensure_file.ts')
-rw-r--r--std/fs/ensure_file.ts42
1 files changed, 22 insertions, 20 deletions
diff --git a/std/fs/ensure_file.ts b/std/fs/ensure_file.ts
index 0d6d7fbc4..e46d7b5f9 100644
--- a/std/fs/ensure_file.ts
+++ b/std/fs/ensure_file.ts
@@ -2,6 +2,7 @@
import * as path from "../path/mod.ts";
import { ensureDir, ensureDirSync } from "./ensure_dir.ts";
import { getFileInfoType } from "./utils.ts";
+const { lstat, lstatSync, writeFile, writeFileSync, ErrorKind } = Deno;
/**
* Ensures that the file exists.
@@ -9,27 +10,28 @@ import { getFileInfoType } from "./utils.ts";
* exist.
* these directories are created. If the file already exists,
* it is NOTMODIFIED.
+ * Requires the `--allow-read` and `--alow-write` flag.
*/
export async function ensureFile(filePath: string): Promise<void> {
- let pathExists = false;
try {
// if file exists
- const stat = await Deno.lstat(filePath);
- pathExists = true;
+ const stat = await lstat(filePath);
if (!stat.isFile()) {
throw new Error(
`Ensure path exists, expected 'file', got '${getFileInfoType(stat)}'`
);
}
} catch (err) {
- if (pathExists) {
- throw err;
- }
// if file not exists
- // ensure dir exists
- await ensureDir(path.dirname(filePath));
- // create file
- await Deno.writeFile(filePath, new Uint8Array());
+ if (err instanceof Deno.DenoError && err.kind === ErrorKind.NotFound) {
+ // ensure dir exists
+ await ensureDir(path.dirname(filePath));
+ // create file
+ await writeFile(filePath, new Uint8Array());
+ return;
+ }
+
+ throw err;
}
}
@@ -39,26 +41,26 @@ export async function ensureFile(filePath: string): Promise<void> {
* exist,
* these directories are created. If the file already exists,
* it is NOT MODIFIED.
+ * Requires the `--allow-read` and `--alow-write` flag.
*/
export function ensureFileSync(filePath: string): void {
- let pathExists = false;
try {
// if file exists
- const stat = Deno.statSync(filePath);
- pathExists = true;
+ const stat = lstatSync(filePath);
if (!stat.isFile()) {
throw new Error(
`Ensure path exists, expected 'file', got '${getFileInfoType(stat)}'`
);
}
} catch (err) {
- if (pathExists) {
- throw err;
- }
// if file not exists
- // ensure dir exists
- ensureDirSync(path.dirname(filePath));
- // create file
- Deno.writeFileSync(filePath, new Uint8Array());
+ if (err instanceof Deno.DenoError && err.kind === ErrorKind.NotFound) {
+ // ensure dir exists
+ ensureDirSync(path.dirname(filePath));
+ // create file
+ writeFileSync(filePath, new Uint8Array());
+ return;
+ }
+ throw err;
}
}