see if a file exists on file system asyncronously in typescript

You can check if a file exists on file system asynchronously in TypeScript using the built-in fs module of Node.js. Here's an example code snippet:

index.ts
import fs from 'fs';

async function checkFileExists(filePath: string): Promise<boolean> {
  return new Promise((resolve) => {
    fs.access(filePath, fs.constants.F_OK, (err) => {
      if (err) {
        resolve(false);
      } else {
        resolve(true);
      }
    });
  });
}
284 chars
14 lines

In the above code, we are importing the fs module and defining an async function checkFileExists that takes the file path as input and returns a promise of boolean.

We are then creating a new promise that resolves to true if the file exists, and to false if it doesn't. To check whether the file exists or not, we are using the fs.access method, which checks if a file exists on the file system or not. We are passing the fs.constants.F_OK flag as the second argument to this method, which indicates that we want to check if the file exists.

If the file does not exist or there is an error while accessing the file, the callback function passed as the third argument to the access method returns an error. In this case, we resolve the promise with false, indicating that the file does not exist. Otherwise, we resolve the promise with true.

gistlibby LogSnag