Skip to content

Commit

Permalink
feat(file-io): add ensureDir()
Browse files Browse the repository at this point in the history
  • Loading branch information
postspectacular committed Feb 18, 2024
1 parent a1b91f9 commit 8ca3085
Showing 1 changed file with 15 additions and 8 deletions.
23 changes: 15 additions & 8 deletions packages/file-io/src/dir.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,16 @@
import { existsSync, mkdirSync, statSync } from "fs";
import { sep } from "path";
import { dirname } from "path";

/**
* Assumes given path is to a directory. Checks if the dir exists and if not
* attempts to create it and then returns true. Otherwise returns false.
*
* @param dir
*/
export const ensureDir = (dir: string) =>
dir.length > 0 && !existsSync(dir)
? (mkdirSync(dir, { recursive: true }), true)
: false;

/**
* Checks if the directory for given file `path` already exists, and if not the
Expand All @@ -11,15 +22,11 @@ import { sep } from "path";
*
* @param path
*/
export const ensureDirForFile = (path: string) => {
const dir = path.substring(0, path.lastIndexOf(sep));
return dir.length > 0 && !existsSync(dir)
? (mkdirSync(dir, { recursive: true }), true)
: false;
};
export const ensureDirForFile = (path: string) => ensureDir(dirname(path));

/**
* Returns true if `path` is a directory (assumes path exists).
* Returns true if `path` is a directory (assumes path exists, if not throws an
* error).
*
* @param path
*/
Expand Down

0 comments on commit 8ca3085

Please sign in to comment.