Here is an example of how to check if a file exists on the file system asynchronously using Promises in TypeScript:
index.ts473 chars24 lines
Explanation:
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.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.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
.filePath
variable is initialized with the path to the file to check for existence.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.ts0 chars1 lines
gistlibby LogSnag