feat: update deno-commons-mod.ts
This commit is contained in:
@@ -3,6 +3,7 @@
|
||||
|
||||
import { assert } from "jsr:@std/assert/assert";
|
||||
import { assertEquals } from "jsr:@std/assert";
|
||||
import { dirname } from "https://deno.land/std@0.208.0/path/mod.ts";
|
||||
|
||||
export async function sleep(timeoutMillis: number): Promise<void> {
|
||||
await new Promise(resolve => setTimeout(resolve, timeoutMillis))
|
||||
@@ -235,6 +236,55 @@ class Logger {
|
||||
|
||||
export const log = new Logger();
|
||||
|
||||
export function getHomeDir(): string | null {
|
||||
if (Deno.build.os === "windows") {
|
||||
return Deno.env.get("USERPROFILE") || Deno.env.get("HOMEDRIVE") + Deno.env.get("HOMEPATH") || null;
|
||||
}
|
||||
return Deno.env.get("HOME") || null;
|
||||
}
|
||||
|
||||
export function resolveFilename(filename: string): string {
|
||||
if (filename.startsWith("~/")) {
|
||||
return getHomeDir() + filename.substring(1);
|
||||
}
|
||||
return filename;
|
||||
}
|
||||
|
||||
export async function existsPath(path: string): Promise<boolean> {
|
||||
try {
|
||||
const stat = await Deno.stat(path);
|
||||
return stat != null;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export async function readFileToString(filename: string): Promise<string | null> {
|
||||
try {
|
||||
return await Deno.readTextFile(resolveFilename(filename));
|
||||
} catch (e) {
|
||||
if (e instanceof Error && e.name == 'NotFound') {
|
||||
return null;
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
export async function writeStringToFile(filename: string, data: string | null): Promise<void> {
|
||||
const newFilename = resolveFilename(filename);
|
||||
if (data == null) {
|
||||
if (await existsPath(newFilename)) {
|
||||
await Deno.remove(newFilename)
|
||||
}
|
||||
} else {
|
||||
const parentDirname = dirname(newFilename);
|
||||
if (!await existsPath(parentDirname)) {
|
||||
await Deno.mkdir(parentDirname, {recursive: true});
|
||||
}
|
||||
await Deno.writeTextFile(newFilename, data);
|
||||
}
|
||||
}
|
||||
|
||||
Deno.test("isOn", () => {
|
||||
assertEquals(false, isOn(undefined));
|
||||
assertEquals(false, isOn(""));
|
||||
|
||||
Reference in New Issue
Block a user