see if a directory exists on file system asyncronously using promises in typescript

To check if a directory exists on the file system using promises and async/await in TypeScript, we can make use of the fs module of Node.js.

Here's the code:

index.ts
import { promises as fs } from 'fs';

async function directoryExists(path: string): Promise<boolean> {
  try {
    await fs.access(path);
    return true;
  } catch (error) {
    if (error.code === 'ENOENT') {
      return false;
    } else {
      throw error;
    }
  }
}
274 chars
15 lines

In this code, we first import the promises module from the fs module. Then, we define an async function called directoryExists that takes a path parameter and returns a Promise<boolean>.

Inside the try block, we use await to call the access method of the fs module. This method checks if the directory exists and is accessible. If it exists, the Promise will be resolved and the function will return true.

If an error is caught, we check if the error has a code property equal to 'ENOENT'. This error code means "No such file or directory". If this is the case, it means that the directory doesn't exist, so we return false. Otherwise, we re-throw the error.

We can use this function like this:

index.ts
const path = '/path/to/directory';
const exists = await directoryExists(path);
console.log(exists); // true or false
117 chars
4 lines

Note that if you're using an older version of Node.js that doesn't support the promises module in the fs module, you can use the exists method instead of access. This method is not async/await, so you'll have to use Promise.resolve and Promise.reject to handle the result. Here's an example:

index.ts
import { exists } from 'fs';

function directoryExists(path: string): Promise<boolean> {
  return new Promise<boolean>((resolve, reject) => {
    exists(path, (exists: boolean) => {
      resolve(exists);
    });
  });
}
221 chars
10 lines

This code defines a function that returns a new Promise. Inside the Promise, it uses the exists method of the fs module to check if the directory exists. If it does, it resolves the Promise with true. Otherwise, it resolves with false. If there's an error, it rejects the Promise with the error.

gistlibby LogSnag