diff options
author | Evgeniy Karagodin <ekaragodin@gmail.com> | 2019-06-24 22:08:06 +0700 |
---|---|---|
committer | Ryan Dahl <ry@tinyclouds.org> | 2019-06-24 08:08:06 -0700 |
commit | 58bac5dc298a5ef16efd664bc9ea951856f901ee (patch) | |
tree | f291ff7084fbe8f4445b0fb387e5015227336a3d /os | |
parent | 69d4d88b4f00b26112ad1d31fd551b032884f0d8 (diff) |
Add userHomeDir (denoland/deno_std#521)
Original: https://github.com/denoland/deno_std/commit/ff7fb5a5d696256b232f8435c53087d5b12848ab
Diffstat (limited to 'os')
-rw-r--r-- | os/README.md | 16 | ||||
-rw-r--r-- | os/mod.ts | 26 | ||||
-rw-r--r-- | os/test.ts | 8 |
3 files changed, 50 insertions, 0 deletions
diff --git a/os/README.md b/os/README.md new file mode 100644 index 000000000..0f2ea810b --- /dev/null +++ b/os/README.md @@ -0,0 +1,16 @@ +# os + +Module provide platform-independent interface to operating system functionality. + +## Usage + +### userHomeDir + +Returns the current user's home directory. On Unix, including macOS, it returns the \$HOME environment variable. On Windows, it returns %USERPROFILE%. +Needs permissions to access env (--allow-env). + +```ts +import { userHomeDir } from "https://deno.land/std/os/mod.ts"; + +userHomeDir(); +``` diff --git a/os/mod.ts b/os/mod.ts new file mode 100644 index 000000000..a2bb0457b --- /dev/null +++ b/os/mod.ts @@ -0,0 +1,26 @@ +// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. + +/** + * Returns the current user's home directory. + * On Unix, including macOS, it returns the $HOME environment variable. + * On Windows, it returns %USERPROFILE%. + * Needs permissions to access env (--allow-env). + * + * Ported from Go: https://github.com/golang/go/blob/go1.12.5/src/os/file.go#L389 + */ +export function userHomeDir(): string { + let env = "HOME"; + let envErr = "$HOME"; + + if (Deno.platform.os === "win") { + env = "USERPROFILE"; + envErr = "%USERPROFILE%"; + } + + const value = Deno.env()[env]; + if (value !== "") { + return value; + } + + throw new Error(`Environment variable '${envErr}' is not defined.`); +} diff --git a/os/test.ts b/os/test.ts new file mode 100644 index 000000000..f1993f22b --- /dev/null +++ b/os/test.ts @@ -0,0 +1,8 @@ +// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. +import { test } from "../testing/mod.ts"; +import { assertNotEquals } from "../testing/asserts.ts"; +import { userHomeDir } from "./mod.ts"; + +test(function testUserHomeDir(): void { + assertNotEquals(userHomeDir(), ""); +}); |