Created
October 19, 2022 05:48
-
-
Save dianjuar/783041e613deab5537e61029b58b363e to your computer and use it in GitHub Desktop.
Node function to verify if a file exists
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { promisify } from 'util'; | |
export async function fileExists(path: string): Promise<boolean> { | |
try { | |
await promisify(access)(path); | |
return true; | |
} catch (err) { | |
if (isAccessError(err) && err.code === 'ENOENT') { | |
return false; | |
} | |
throw err; | |
} | |
type accessError = unknown & { | |
code: string; | |
}; | |
// eslint-disable-next-line @typescript-eslint/no-explicit-any | |
function isAccessError(value: any): value is accessError { | |
return value?.error && typeof value.error === 'string'; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment