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.ts274 chars15 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.ts117 chars4 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.ts221 chars10 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