summaryrefslogtreecommitdiff
path: root/fs/ensure_file.ts
diff options
context:
space:
mode:
authorAxetroy <troy450409405@gmail.com>2019-04-07 09:01:23 +0800
committerRyan Dahl <ry@tinyclouds.org>2019-04-07 04:01:23 +0300
commitd6f808958f414315a09b3429cf0c4b5c258f1012 (patch)
treed2d60398319ba1bcd3f11216b258d835941ef45f /fs/ensure_file.ts
parent9d1e24b67baf59d1d8b9bd1eb2a6c4135c6e7ca4 (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_file.ts')
-rw-r--r--fs/ensure_file.ts29
1 files changed, 25 insertions, 4 deletions
diff --git a/fs/ensure_file.ts b/fs/ensure_file.ts
index 56632f150..6fe8e7822 100644
--- a/fs/ensure_file.ts
+++ b/fs/ensure_file.ts
@@ -1,6 +1,7 @@
// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
import * as path from "./path/mod.ts";
import { ensureDir, ensureDirSync } from "./ensure_dir.ts";
+import { getFileInfoType } from "./utils.ts";
/**
* Ensures that the file exists.
@@ -8,10 +9,20 @@ import { ensureDir, ensureDirSync } from "./ensure_dir.ts";
* these directories are created. If the file already exists, it is NOT MODIFIED.
*/
export async function ensureFile(filePath: string): Promise<void> {
+ let pathExists = false;
try {
// if file exists
- await Deno.stat(filePath);
- } catch {
+ const stat = await Deno.lstat(filePath);
+ pathExists = true;
+ 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));
@@ -26,10 +37,20 @@ export async function ensureFile(filePath: string): Promise<void> {
* these directories are created. If the file already exists, it is NOT MODIFIED.
*/
export function ensureFileSync(filePath: string): void {
+ let pathExists = false;
try {
// if file exists
- Deno.statSync(filePath);
- } catch {
+ const stat = Deno.statSync(filePath);
+ pathExists = true;
+ 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));