The JS runtimes
Published in

The JS runtimes

Deno nuggets: Check if a file exists

This article is a part of the Deno nuggets series, where each article attempts to suggest a pointed solution to a specific question that can be read in less than a minute. There is no ordering of nuggets.

Problem

How to check if a file exists?

$ ls /var/tmp/a.txt
cat: /var/tmp/a.txt: No such file or directory
$ ls /var/tmp/testdata/sample.txt
Learning Deno Is Fun!

Solution

Imports

No imports are required

Perform operation directly

Deno’s standard library used to have an API called exists() that was used to check if a file exists. This API has now been deprecated, citing race conditions (check here). The same functionality has been removed from Node.js too (check here).

The recommended way is to perform the operation directly and look for errors. For example —

  • Open the file directly and check for errors
  • Stat the file directly and check for errors
  • Read the file directly and check for errors
  • etc.

The specific error to look for is Deno.errors.NotFound. This error would indicate that the file was not found.

Let’s look at some examples:

try {
const f=await Deno.open('/var/tmp/a.txt');
} catch(e) {
if(e instanceof Deno.errors.NotFound)
console.error('file does not exists');
}
//file does not existstry {
const f=await Deno.stat('/var/tmp/a.txt');
} catch(e) {
if(e instanceof Deno.errors.NotFound)
console.error('file does not exists');
}
//file does not existstry {
const s=await Deno.readTextFile('/var/tmp/testdata/sample.txt');
} catch(e) {
if(e instanceof Deno.errors.NotFound)
console.error('file does not exists');
}
//s -> Learning Deno Is Fun!

This story is a part of the exclusive medium publication on Deno: Deno World.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store