How can one check if a file or directory exists using Deno?
There is no function that's specifically for checking if a file or directory exists, but the Deno.stat
function, which returns metadata about a path, can be used for this purpose by checking the potential errors against Deno.ErrorKind.NotFound
.
const exists = async (filename: string): Promise<boolean> => {
try {
await Deno.stat(filename);
// successful, file or directory must exist
return true;
} catch (error) {
if (error && error.kind === Deno.ErrorKind.NotFound) {
// file or directory does not exist
return false;
} else {
// unexpected error, maybe permissions, pass it along
throw error;
}
}
};
exists("test.ts").then(result =>
console.log("does it exist?", result)); // true
exists("not-exist").then(result =>
console.log("does it exist?", result)); // false
There is the standard library implementation, here: https://deno.land/std/fs/mod.ts
import {existsSync} from "https://deno.land/std/fs/mod.ts";
const pathFound = existsSync(filePath)
console.log(pathFound)
This code will print true
if the path exists and false
if not.
And this is the async implementation:
import {exists} from "https://deno.land/std/fs/mod.ts"
exists(filePath).then((result : boolean) => console.log(result))
Make sure you run deno with the unstable flag and grant access to that file:
deno run --unstable --allow-read={filePath} index.ts
The Deno API changed since the release of Deno 1.0.0
. If the file is not found the exception raised is Deno.errors.NotFound
const exists = async (filename: string): Promise<boolean> => {
try {
await Deno.stat(filename);
// successful, file or directory must exist
return true;
} catch (error) {
if (error instanceof Deno.errors.NotFound) {
// file or directory does not exist
return false;
} else {
// unexpected error, maybe permissions, pass it along
throw error;
}
}
};
exists("test.ts").then(result =>
console.log("does it exist?", result)); // true
exists("not-exist").then(result =>
console.log("does it exist?", result)); // false
As the original answer account is suspended and cannot change his answer if I comment on it, I'm reposting a fixed code snippet.
The exists
function is actually part of the std/fs module although it is currently flagged as unstable. That means you need to deno run --unstable
: https://deno.land/std/fs/README.md#exists