by Sai gowtham

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.

app.js
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.

app.js
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:

app.js
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.

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
130,921 students enrolled
21 hours of video content
View Course