How to check if a file exists in Deno
In this tutorial, we are going to learn about how to check if a file or directory exists in Deno using the fs module.
The exists() method
We can use the exists()
method to check if a file exists or not in the file system.
The exists()
method takes the file path
as an argument and returns the promise boolean where result
value is true
if a file exists or result
value is false
if a file doesn’t exist.
The exists() method works asynchronously.
import { exists} from "https://deno.land/std/fs/mod.ts";
exists("./math.js").then((result) => console.log(result));
To run the above code, we need to allow deno to read the ./math.js
file by using --allow-read
flag.
deno run --unstable --allow-read=./math.js app.js
Output:
true
Note: All the methods inside an fs module are currently unstable, so that we have used the
--unstable
flag to enable it during the runtime.
The existsSync() method
The existsSync()
method is used to check the file existence synchronously.
The existsSync()
method takes the file path
as an argument and returns true
if a file exists else it returns false
.
import {existsSync } from "https://deno.land/std/fs/mod.ts";
if (existsSync("./math.js")) {
console.log("file is found");
} else {
console.log("file is not found");
}
deno run --unstable --allow-read=./math.js app.js
Output:
file is found
Checking the directory exists
Similarly, you can also use the above methods to check if a directory exists or not.
Example:
import {exists, existsSync} from "https://deno.land/std/fs/mod.ts";
// asynchronous
exists("./images").then((result) => console.log(result));
// synchronous
if (existsSync("./images")) {
console.log("file is found");
} else {
console.log("file is not found");
}
In the above code, we are checking for a ./images
directory existence in a file system.