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

Here is an example of how to check if a file exists on the file system asynchronously using Promises in TypeScript:

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

async function fileExists(filePath: string): Promise<boolean> {
  try {
    await fs.access(filePath);
    return true;
  } catch (error) {
    if (error.code === 'ENOENT') {
      return false;
    } else {
      throw error;
    }
  }
}

const filePath = '/path/to/file.txt';
fileExists(filePath)
  .then((exists) => {
    console.log(`File "${filePath}" exists: ${exists}`);
  })
  .catch((error) => {
    console.error(error);
  });
473 chars
24 lines

Explanation:

  1. The promises module from the Node.js fs module is imported using ES6 destructuring syntax. This module provides asynchronous versions of file system functions that return Promises.
  2. The fileExists function is created using the async keyword to make it asynchronous and the Promise<boolean> return type to indicate that it returns a Promise that resolves with a boolean indicating whether the file exists on the file system.
  3. The access function from the fs module is called with the filePath argument inside a try/catch block. If the file exists, the access function will resolve successfully and the fileExists function will return true. If the file does not exist, the access function will reject with an ENOENT error, which means "no such file or directory". In this case, the fileExists function catches the error and returns false.
  4. The filePath variable is initialized with the path to the file to check for existence.
  5. The fileExists function is called with filePath, and the resulting Promise is handled using .then() and .catch() methods. If the Promise resolves successfully, the .then() method logs a message indicating whether the file exists or not. If the Promise rejects with an error, the .catch() method logs the error.
index.ts
0 chars
1 lines

gistlibby LogSnag