diff options
| author | Axetroy <troy450409405@gmail.com> | 2019-04-07 09:01:23 +0800 |
|---|---|---|
| committer | Ryan Dahl <ry@tinyclouds.org> | 2019-04-07 04:01:23 +0300 |
| commit | d6f808958f414315a09b3429cf0c4b5c258f1012 (patch) | |
| tree | d2d60398319ba1bcd3f11216b258d835941ef45f /fs/ensure_dir.ts | |
| parent | 9d1e24b67baf59d1d8b9bd1eb2a6c4135c6e7ca4 (diff) | |
fix: ensure exists file/dir must be the same type or it will throw error (denoland/deno_std#294)
Original: https://github.com/denoland/deno_std/commit/24f41f67bdbc9f426e3f9f03598a1010748d8200
Diffstat (limited to 'fs/ensure_dir.ts')
| -rw-r--r-- | fs/ensure_dir.ts | 30 |
1 files changed, 25 insertions, 5 deletions
diff --git a/fs/ensure_dir.ts b/fs/ensure_dir.ts index e7e4f69a2..dfc02f35c 100644 --- a/fs/ensure_dir.ts +++ b/fs/ensure_dir.ts @@ -1,14 +1,24 @@ // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. - +import { getFileInfoType } from "./utils.ts"; /** * Ensures that the directory exists. * If the directory structure does not exist, it is created. Like mkdir -p. */ export async function ensureDir(dir: string): Promise<void> { + let pathExists = false; try { // if dir exists - await Deno.stat(dir); - } catch { + const stat = await Deno.stat(dir); + pathExists = true; + if (!stat.isDirectory()) { + throw new Error( + `Ensure path exists, expected 'dir', got '${getFileInfoType(stat)}'` + ); + } + } catch (err) { + if (pathExists) { + throw err; + } // if dir not exists. then create it. await Deno.mkdir(dir, true); } @@ -19,10 +29,20 @@ export async function ensureDir(dir: string): Promise<void> { * If the directory structure does not exist, it is created. Like mkdir -p. */ export function ensureDirSync(dir: string): void { + let pathExists = false; try { // if dir exists - Deno.statSync(dir); - } catch { + const stat = Deno.statSync(dir); + pathExists = true; + if (!stat.isDirectory()) { + throw new Error( + `Ensure path exists, expected 'dir', got '${getFileInfoType(stat)}'` + ); + } + } catch (err) { + if (pathExists) { + throw err; + } // if dir not exists. then create it. Deno.mkdirSync(dir, true); } |
